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)); } }
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)); } }
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.
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; }