Wednesday, 19 September 2012

TDD with Hamcrest

You may not be getting the most out of your TDD and JUnit, Hamcrest provides some additions. Hamcrest allows you to make your assertions more fluent and get better error messages.

Hamcrest equalTo()

Although not necessary, some developers like to use is and equalTo together because it feels more fluent to them. This is the very reason for is's existence: to make use of other matchers more fluent.

   public void testWithHamcrestEqualTo()  
       final int result = 5*2;  
       assertThat(result, equalTo(10));  

Hamcrest sameInstance()

You can test for object identity using sameInstance, this test also shows a not matcher that negates a logical condition.
   public void testWithHamcrestNotSameInstance()  
       final BigDecimal expectedResult = new BigDecimal(6*2);  
       final BigDecimal result = new BigDecimal(6*2);  
       assertThat(result, not(sameInstance(expectedResult)));  

Hamcrest nullValue() and notNullValue()  

You can test for null values like so :-

   public void testHamcrestIsNull()  
       final String s = null;  
       assertThat(s, is(nullValue()));  
   public void testHamcrestNotNull()  
       final String s = "String";  
       assertThat(s, notNullValue());  

Hamcrest greaterThan(), etc...

Hamcrest has the usual relational operators you might expect.

   public void testHamcrestGreaterThan() {  
     assertThat(2, greaterThan(1));      

Hamcrest instanceOf()

You can test for the class type of an object using the instanceOf matcher.

   public void testHamcrestInstanceOf()  
       Date now = new Date();  
       assertThat(now, instanceOf(Date.class));  

Hamcrest containsInAnyOrder()

This is useful for checking collections contain certain elements when you don't care about the entire collection or the order.
     @Test public void testHamcrestContainsInAnyOrder() {  
       final Set<String> set = new HashSet<String>();   
       assertThat(set, containsInAnyOrder("one", "two"));  

Hamcrest hasProperty()

This is useful to access JavaBean properties.

   @Test public void testHamcrestHasProperty() {  
       Button test = new Button("Hello");  
     assertThat(test, hasProperty("label", equalTo("Hello")));  

The Hamcrest works with JUnit 4 and you can download it here.
Example source here.

No comments:

Post a Comment