Hansel Tutorial

This tutorial assumes that you are familiar with JUnit 4 and shows the way to add code coverage testing to an existing JUnit TestCase.

Start

Let's assume that we want to test the Example class:
public class Example {
    public int abs(int i) {
        if (i > 0) {
            return i;
        } else {
            return -i;
        }
    }
}
We have an existing JUnit4 TestCase:
public class ExampleJUnit4Test {
     
    @Test public void absTest() {
        Example example = new Example();
        assertEquals("abs(1) should be 1.", 1, example.abs(1));
        assertEquals("abs(0) should be 0.", 0, example.abs(0)); 
     } 

    /**
     * Test the Example.add() method. This also covers the code of the inner
     * class.
     */
    @Test public void innerClassTest() {
        Example example = new Example();  
        assertEquals("add(2, 3) should be 5.", 5, example.add(2, 3));
    }    
}

Adding Code Coverage Testing

Since we are not sure, that the test covers all lines of the Example class, we want to make sure and add coverage testing to the test case. So we create a new coverage suite:
  
@RunWith(CoverageRunner.class)
@Suite.SuiteClasses({ ExampleJUnit4Test.class })
@CoverageRunner.CoverClasses({ Example.class })
public class ExampleJUnit4Suite {

}

Running the Test

Now we are ready to run the test. Instead of running the test directly, we start the test suite. Also the parameter "-javaagent:hansel.jar" has to be passed to the VM running the Testsuite (how to do this in exlipse is described here). When running the suite we unfortunatly get an failure:
Test 'org.hanselexample.ExampleTest' does not cover line(s) [20] in org.hanselexample.Example.abs(I)I.
Looking at the code, the mistake we made is obvious: We didn't test the absolute value of a negativ number. After correcting the test method:
    @Test public void absTest() {
        Example example = new Example();
        assertEquals("abs(1) should be 1.", 1, example.abs(1));
        assertEquals("abs(-1) should be 1.", 1, example.abs(-1));
        assertEquals("abs(0) should be 0.", 0, example.abs(0)); 
     } 
the test runs without any problems.

Beware

Covering all the code of a class with a test case does not mean, there are no bugs. Writing good test cases is still hard, but I hope Hansel will help to make life a little easier.