Test infrastructure, part 3 - Matching with Hamcrest

A word on Hamcrest, a library which integrates with JUnit to improve test readability.

When checking if two objects obj1 and obj2 are equals, the "classic" JUnit way is to write something like:

import org.junit.Test;

class Test

   @Test
   public void equalsTest(){  
  
      assertEquals(ob1, obj2);
      //is obj1 the expected or actual result ? 
      //not clear without resorting to the javadoc 
   }
}

with Hamcrest - the test reads (almost) like plain ordinary english and it is easier to see that obj1 is the actual result and obj2 is the expected result:

import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat; 
import static org.hamcrest.Matchers.is;

class Test{

   @Test
   public void equalsTest(){
      //asserts that the actual result is what's expected.
      assertThat (obj1, is(obj2));
   }
}


The above illustrates the use of the is() matcher, there are many other matchers to choose from... Just to name a few:

//hasEntry matcher
Map aMap = new HashMap ();
amap.put("test",123);
assertThat (aMap, hasEntry("test",123);

//greaterThan matcher
assertThat(stuff.size(), greaterThan(0));

//combining is and not matchers
assertThat (stuff.size(), is(not(0)))x

//assert that an array contains certain elements
String [] array1 =....;
assertThat (array1, allOf(hasItemInArray("element1"), hasItemInArray("element2")));

No comments:

Post a Comment