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( ) .

Example 4-3. Test comparing two Books using their title attributes
 LibraryTest.java    public void  testGetBooks  ( ) {       Book book = library.getBook( "Dune" );       assertTrue( book.getTitle( ).equals( "Dune" ) );       book = library.getBook( "Solaris" );       assertTrue( book.getTitle( ).equals( "Solaris" ) );    } 

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.

Example 4-4. Custom assert method to compare Books
 BookTest.java public class  BookTest  extends TestCase {  public static void assertEquals( Book expected, Book actual )  {       assertTrue(expected.getTitle( ).equals( actual.getTitle( ) )               && expected.getAuthor( ).equals( actual.getAuthor( ) ));    } } 

The assert method assertEquals() takes expected and actual Book objects to compare. It succeeds if the title and author attributes of the two Book s are equal. Example 4-5 shows how it is used.

Example 4-5. Using the custom assert method
 LibraryTest.java public class  LibraryTest  extends TestCase {    private Library library;    private Book book1, book2;    public void  setUp( )  {       library = new Library( );       book1 = new Book("Dune", "Frank Herbert");       book2 = new Book("Solaris", "Stanislaw Lem");       library.addBook(  book1  );       library.addBook(  book2  );    }    public void  testGetBooks( )  {       Book book = library.getBook( "Dune" );       BookTest.assertEquals( book1, book );       book = library.getBook( "Solaris" );       BookTest.assertEquals( book2, book );    } } 

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.

Unit Test Frameworks
Unit Test Frameworks
ISBN: 0596006896
EAN: 2147483647
Year: 2006
Pages: 146
Authors: Paul Hamill

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net