Using JRuby for Java testing?
A recent article on InfoQ (Boost your Java Test with Ruby and JtestR) described a new framework for doing Java testing using JRuby. The article includes the following test case to highlight it’s features.
import java.util.HashMap
describe "An empty", HashMap do
before :each do
@hash_map = HashMap.new
end
it "should be able to add an entry to it" do
@hash_map.put "foo", "bar"
@hash_map.get("foo").should == "bar"
end
it "should return a keyset iterator that throws an exception on next" do
proc do
@hash_map.key_set.iterator.next
end.should raise_error(java.util.NoSuchElementException)
end
end
What is the point of this example? Is there really a significant difference between this example and the following JUnit4 test class?
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import java.util.HashMap;
import java.util.NoSuchElementException;
import org.junit.Test;
public class HashMapTest {
private HashMap<String,String> hashMap =
new HashMap<String,String>();
@Test
public void shouldBeAbleToAddAnEntryToIt() {
hashMap.put("foo", "bar");
assertThat(hashMap.get("foo"), is("bar"));
}
@Test(expected = NoSuchElementException.class)
public void shouldReturnAKeysetIteratorThatThrowsAnExceptionOnNext() {
hashMap.keySet().iterator().next();
}
}
Sure, the syntax is a bit different and the Java version is slightly more verbose with it’s access specifiers and type declarations. However, the Java version runs fast enough that you don’t need to set up a Ant server to get reasonable performance from your tests (as recommended in the article for JTestR).
I’m not questioning that scripting can be useful in unit tests. However, I’d think that Groovy’s superior Java integration would make it a better choice for this purpose than JRuby. Does anybody know of some compelling, pragmatic examples of the relative benefit of JRuby over Groovy for Java test scripting purposes?
Paul Davis wrote:
Really, they are both great for unit testing java. Often, the setup code for jUnit is bigger (more verbose) than the actual tests being performed.
To offer comparisons, Groovy may be easier (for someone learning a new language) just because it is so close to java and is backwards compatible with it.
On the ruby side, beyond simple unit testing, RSpec is an elegant way to write behavior tests. Probably more elegant than any of the other ways to do it.
Groovy and Ruby are so similar that it’s hard to try to position one above the other.
Posted 10 Jan 2008 at 7:45 pm ¶
Evan Light wrote:
@paul: With regard to Groovy =~ Ruby and Ruby =~ Groovy, not so. Groovy’s metaprogramming API is big on ceremony whereas Ruby’s is simple yet immensely powerful. IMO, Ruby’s pure-OO nature and metaprogramming capabilities are what set it apart from other languages.
Posted 13 May 2008 at 3:50 pm ¶