I used to write the following code quite often in my unit tests:
assertEquals(2, list.size()); assertTrue(list.contains(element1)); assertTrue(list.contains(element2));
In order to reduce duplication these three lines of code can be extracted to a custom assertion:
assertContainsOnlyTheseElements(list, element1, element2)
Instead of writing your own assertions you can use the FEST Assert library. This is how you can express it in FEST:
assertThat(list).hasSize(2).contains(element1, element2);
Or even better:
assertThat(list).containsExactly(element1, element2);
Isn’t it beautiful? It reads almost like a natural language.
It’s also very easy to use because it requires only a single static import from org.fest.assertions.Assertions. The assertThat method is overloaded for multiple different types, each with specific assertions. The error messages in case of assertion failure are also quite user-friendly. For these reasons I prefer to use FEST Assert over Hamcrest for custom assertions.
What about a few examples between a Hamcrest and Fest assertion messages.
Good point. I only mentioned that I prefer Fest over Hamcrest but it’s good idea to write a post with detailed comparison. Thanks!
Pingback: A Cool Technique for Object Comparison in JUnit | Piotr Jagielski's Blog