It is important to test the error-handling behavior of production code in addition to its normal behavior. Such tests generate an error and assert that the error is handled as expected. In other words, an expected error produces a unit test success. The canonical example of a unit test that checks expected error handling is one that tests whether an expected exception is thrown, as shown in Example 4-8. Example 4-8. Unit test for expected exception LibraryTest.java public void testRemoveNonexistentBook( ) { try { library.removeBook( "Nonexistent" ); fail( "Expected exception not thrown" ); } catch (Exception e) {} } The expected error behavior is that an exception is thrown when the removeBook( ) method is called for a nonexistent Book . If the exception is thrown, the unit test succeeds. If it is not thrown, fail() is called. The fail( ) method is another useful variation on the basic assert method. It is equivalent to assertTrue(false) , but it reads better. Since the removeBook( ) method now throws an exception, the testRemoveBook( ) unit test should be updated, as shown in Example 4-9. Example 4-9. Unit test that fails when an exception is thrown LibraryTest.java public void testRemoveBook( ) { try { library.removeBook( "Dune" ); } catch (Exception e) { fail( e.getMessage( ) ); } Book book = library.getBook( "Dune" ); assertNull( "book is not removed", book ); } This example uses fail( ) to cause the test to fail when an unexpected exception is thrown. The exception's message attribute is used as the assert message. The same general pattern is followed to test expected error behavior that is not represented by an exception: the test fails if the error is not seen and succeeds if it is. Example 4-10 shows a unit test that attempts to get a nonexistent Book from the Library and asserts that the expected null Book is returned. Example 4-10. Unit test checking the expected error getting a nonexistent Book LibraryTest.java public void testGetNonexistentBook( ) { Book book = library.getBook( "Nonexistent" ); assertNull( book ); } |