Hansel Tutorial

This tutorial assumes that you are familiar with JUnit 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 JUnit TestCase:
public class ExampleTest extends TestCase {
    public ExampleTest(String name) {
        super(name);
    }

    public void testAbs() {
        Example example = new Example();
        assertEquals(1, example.abs(1));
    } 
}

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 add a method:
   
public static Test suite() {
    return new CoverageDecorator(ExampleTest.class,
                                 new Class[] { Example.class });
} 
This replaces the test with a decorator that performs the coverage testing. The whole test case is now:
public class ExampleTest extends TestCase {
    public ExampleTest(String name) {
        super(name);
    }

    public static Test suite() {
        return new CoverageDecorator(ExampleTest.class,
                                     new Class[] { Example.class });
    } 

    public void testAbs() {
        Example example = new Example();
        assertEquals(1, example.abs(1));
    } 
}

Running the Test

Now we are ready to run the test. This is not different from before. But unfortunatly we 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 correting the test method:
public void testAbs() {
    Example example = new Example();
    assertEquals(1, example.abs(1));
    assertEquals(1, example.abs(-1));
} 
the test runs without any problems.

Assertions

To help using the jdk 1.4 assertion facility, Hansel provides the AssertionCoverageDecorator. This decorator runs the test one time with assertions enabled and one time with assertions disabled.

The following method can help you find out, wether assertions are enabled:

private static boolean assertionsEnabled() {
    boolean enabled = false;
    assert true | (enabled = true);
    return enabled;
}

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.