Chapter 4. Writing Unit Tests
The previous chapters present a simple unit test framework and the fundamentals of xUnit. The unit test framework’s architecture is important to understand, but not something you have to think about often. Most of your time should be spent writing unit tests, implementing production code to make the tests pass, or refactoring. This chapter includes examples of common patterns used when writing unit tests, as well as related tips on unit test development.
The code examples in this chapter are unit tests of additional
virtual library functionality, including looking up books by author
and title, looking up multiple books by one author, and removing
books from the library. The Library and
Book code to implement the new features is given
at the end of the chapter.
Types of Asserts
The code examples shown
so
far use plain asserts
. These are the most generic type of
test assertion, which take a Boolean condition that must evaluate to
TRUE for the test to succeed. A plain assert, the
unit test for the
Library
method
removeBook( ), is shown in Example 4-1.
LibraryTest.java
public void testRemoveBook( ) {
library.removeBook( "Dune" );
Book book = library.getBook( "Dune" );
assertTrue( book == null );
}If the method removeBook( ) is stubbed out, the
test fails. The following test results report the
failure:
> java junit.textui.TestRunner LibraryTests .....F. Time: 0.06 There was 1 failure: 1) testRemoveBook(LibraryTest)junit.framework.AssertionFailedError ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access