I have never used the Hamcrest matchers with JUnit before. Not until last week. I noticed in the release note that JUnit 4.11 included Hamcrest 1.3, with its Matchers and improved assertThat syntax. Reading the examples on the release note, I was intrigued.
To use the new Matchers and assertThat, you need to include the following imports
import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*;
Number Objects
The first improvement I noticed were comparison with Java number objects.
Long l = new Long(10); assertEquals(10L, l); assertThat(l, is(10L));
With the old assertEquals, the compiler would complain about The method assertEquals(Object, Object) is ambiguous for type X. You need to change both parameters to either long values or Long objects for the assert to work, for example
assertEquals(10L, l.longValue());
On the other hand, assertThat and the is() matcher works just fine.
Collections
I saw a few very handy looking matchers for Collections from looking at the CoreMatchers javadoc. For example, hasItem, hasItems, everyItem. I had the opportunity to use hasItems in my unit tests last week to check if a List object contains items from a given list of values. It was as simple to use as this
assertThat(list, hasItems("apples", "oranges"));
I’m a fan of this new way of matching things in JUnit.