Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Tuesday, September 7, 2010

RSpec for Java

I think the reasons why people are using Java are in the following list.

  • The product must run on JVM
  • You are fixing existing code that is written in Java
  • You or your co-workers love Java

Java has some testing frameworks written in Java, but it's difficult to implement something like RSpec due to the limitation of Java syntax. But actually you don't have to use a testing framework in Java but can use RSpec on JRuby, even though the product is not using JRuby.

A minimum example

public class Hello {
  public String world() {
    return "world!";


require 'java'
java_import 'Hello'

describe 'Hello' do
  it 'world' do == 'world!'

Compile and run RSpec command.

$ javac
$ jruby -S spec hello_spec.rb

This works.

If you didn't install RSpec yet, you can install it with the following command.

$ jruby -S gem install rspec

A bit complex example

This approach is powerful; you can use a Java bytecode which was compiled with some special parameters like -target. For example, J2ME programs needs to be compiled as Java 1.4 and needs a jar file as well. You still can spec such program.

import javax.microedition.midlet.MIDlet;

class A extends MIDlet {
  public void destroyApp(boolean unconditional) {
  protected void pauseApp() {
  protected void startApp() {
  static public String f() {
    return "sajdfksadfsd";


require 'java'
java_import 'A'

describe 'A.f' do
  it 'is on java' do
    RUBY_DESCRIPTION.should be_include 'jruby'

  it 'is a strange string' do
    A.f.should == 'sajdfksadfsd'


$ javac -target 1.4 -source 1.4 -g:none -bootclasspath the-jar-file.jar
$ jruby -J-cp the-jar-file.jar:. -S ~/git/jruby/bin/spec a_spec.rb

It works.


  1. What about mocking and stubbing? Have you integrated an existing Java mocking library into the work flow?

  2. I tried to mock a method from RSpec now but failed. Just to re-define an existing method didn't change the behavior of a method call in Java.

    I've never tried existing Java mocking libraries yet. I'm still a Java newbie..