Next page | Contents page |

Further unit testing guidelines

Make sure the tests cover abnormal cases and errors as well as the usual correct runs. Think about boundary cases (extreme values) when writing tests.

In Exercise 30 we could obviously not test all possible values. How many are there? What is a suitable range of values to test? What are the boundary values?

Ensure tests are independent - set up objects afresh for each one, in an @Before method - only set up the minimum required objects though.

Do not use the Java keyword assert. It is not handled by the JUnit test environment. It has a completely separate reporting mechanism.

All of the annotations

All of the annotated methods must be public. In earlier versions of JUnit that was not necessary - could be protected.

equals ()

Note that if we want to use org.junit.Assert.assertEquals() on two objects we had better take care that the objects do have sensible equals() methods. Not many API classes override equals() but String and java.util.Date do.

JUnit 4 is also better than earlier versions on comparing float and double variables - overloaded assertEquals() versions for these have a tolerance parameter.

Testing exceptions

If an unexpected exception occurs the JUnit runner will report it as a failure, so there is nothing to do if that is the intention. But if you want to test that an exception is thrown when it should be (as in Exercise 30):

	@Test 
	public void testThrowingNullPointerException ()
	{
		try
		{
			methodUnderTest (somethingToCauseNullPointerException);
			org.junit.Assert.fail (); // Should not get here 
		}
		catch (NullPointerException ex)
		{
			// May be nothing to do here - but comment that
		}  
	}

Line coverage

Automated unit testing should be able to test every line in every class under test. There are coverage tools available as plug-ins for both NetBeans and Eclipse. They highlight lines in different colours after JUnit tests have run, to show which lines of your code were exercised by the tests.

Google for the plug-in for your IDE and download.

Next page | Contents page |