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
Hello.java
public class Hello {
public String world() {
return "world!";
}
}
hello_spec.rb
require 'java'
java_import 'Hello'
describe 'Hello' do
it 'world' do
Hello.new.world.should == 'world!'
end
end
Compile Hello.java and run RSpec command.
$ javac Hello.java
$ 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.
A.java
import javax.microedition.midlet.MIDlet;
class A extends MIDlet {
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
protected void pauseApp() {
}
protected void startApp() {
}
static public String f() {
return "sajdfksadfsd";
}
}
a_spec.rb
require 'java'
java_import 'A'
describe 'A.f' do
it 'is on java' do
RUBY_DESCRIPTION.should be_include 'jruby'
end
it 'is a strange string' do
A.f.should == 'sajdfksadfsd'
end
end
run
$ javac -target 1.4 -source 1.4 -g:none -bootclasspath the-jar-file.jar A.java
$ jruby -J-cp the-jar-file.jar:. -S ~/git/jruby/bin/spec a_spec.rb
It works.