4.2 Defining Custom Asserts

The basic assert methods cover only a few common cases. It's often useful to extend them to cover additional test conditions and data types. Custom assert methods save test coding effort and make the test code more readable.

So far, the Library tests check a Book 's title attribute to verify the expected Book object, as shown in Example 4-3 in the test method testGetBooks( ) .

To be really sure that the test Book is correct, the tests should also check the Book 's author, but this means adding extra asserts to each test. It's clearly useful to have an assert method that compares an expected Book to the actual Book , checking all of the attributes. This new assert method is easy to implement by building on the generic assertTrue() method, as shown in Example 4-4.

The custom assert method makes the test clear and concise and improves it by comparing all the Book attributes, not just the title. While writing tests, watch for complex assert conditions that are used repeatedly. They are good candidates for replacement with custom assert methods.