Monday, February 20, 2012

FEST Assertions, part 1: state intent in tests

I need to express my tests in such a way, that they become clear and easy to follow. A regular xUnit test will surely contain a couple of assertions, ensuring state validation for SUT.

Take a look at the code below; I'm sure you recognize the standard org.junit.Assert assertions:

@Test
public void someTest() {
 // ... test code -- fixture, etc ...

 assertNotNull(invoice);
 assertNotNull(invoice.getBillingAddress());
 assertNotNull(invoice.getBillingAddress().getStreet());
 assertEquals(billingAddress, invoice.getBillingAddress());
 
 // possibly other assertions, invoice can be a pretty 
 // complex object.
}

As you can see, for even such simple objects, the assertions tend to be lengthy and hard to follow; another down-side is the lack of expresivity -- test is not explicit enough. For now, let's use the build-in assertions from FEST; while total number of lines hasn't changed, still the code ends up cleaner and explicit:
@Test
public void someTest() {
 // ... test code -- fixture, etc ...

        assertThat(invoice).isNotNull();
        assertThat(invoice.getBillingAddress())
          .isNotNull()
          .isEqualTo(billingAddress);
 
 // possibly other assertions, invoice can be a pretty 
 // complex object.
}

Source code available here.