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.
@Before
- annotates method to be run before every @Test
method - equivalent to setUp()
in v3.8 and earlier versions@After
- to run after every test - equivalent to old tearDown()
@BeforeClass
- run once before all tests@AfterClass
- run once after all tests@Test
- method is to be run as a test@Test(expected=X)
, where X is a comma-separated list of class literals, for subclasses of java.lang.Throwable
- tells test environment not to treat listed exception types as failures, if they occur.All of the annotated methods must be public. In earlier versions of JUnit that was not necessary - could be protected.
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.
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
}
}
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.