Monday, April 18, 2011

What is good for Ruby is good for Java: JSpec

People familiar with Ruby will invariably learn RSpec. RSpec is a great library for writing specifications, or specs as Ruby developers call them. Some time ago, I developed JSpec somewhat modeled after RSpec. I needed a better language for writing expectations. What is an expectation and how is it different from assertion?

In a Java tests, people usually use assertions to check conditions after some code is executed, such as:

assertEquals(stirng1, string1); 

In the case above if string1 and string2 are not equal, the assertion fails thus failing the test. In general, having a test is much better than not having one, but after learning RSpec, I really felt that the asserts are inadequate.
Asserts are an old way of saying: "I have developed code, and I will check that it works". I really prefer a more modern TDD/BDD approach that says: "I captured requirements of a system in test code, and will implement it after". This allows me to develop the implementation of my system after I write a specification. There is so much written on the virtues of good TDD/BDD development. Those interested should at least watch this: Dave Astels BDD presentation.

As part of the work I did while working on ActiveJDBC , I developed the JSpec library.
The main idea is to replace "assert" language with "should" language and make it as close to English as possible. This forces the brain to work in a different mode, writing a "specification of behavior" for your program rather than "assertion" that the program works. The difference might seem subtle, but requires a different style of thinking and promotes true TDD/BDD - when specifications are written before implementation, sometimes even by different people.

Here is an example of "standard" JUnit code:
@Test
public void testCalculator(){
   Calculator c = new Calculator();
   c.add(2, 2);
   assertEquals(c.result(), 4);
}
and here is the same written in JSpec (also with JUnit):
@Test
public void shouldAddNumbersCorrectly(){
   Calculator c = new Calculator();
   c.add(2, 2);
   a(c.result()).shouldBeEqual(4);
}

As you can see, the difference is subtle, but profound. More information on the use of this library can be found here: http://code.google.com/p/activejdbc/wiki/JSpec


happy coding!
igor

1 comment:

Anonymous said...

It is very helpful!