Matchers along with assertThat were introduced in JUnit 4.4. assertThat provides a way to write clean highly readable assertions, taking advantage of matchers. These matchers are provided by a library called Hamcrest. Little secret, Hamcrest is an anagram of Matchers.
Let’s compare them to analyse the benefits of using assertThat.
int c = 5 * 5; assertEquals(25, c); assertThat(c, is(equalTo(25)));
So to recap the last lesson, the first example ‘assertEquals(25, c)’ actually reads ‘assert equals
Then there are the error messages by default when an assert fails. With assertEquals you’ll get:
java.lang.AssertionError: Expected :20 Actual :25
With the assertThat, you’ll get
java.lang.AssertionError: Expected: is <20> but: was <25>
A subtle difference, but a very welcomed one when you’re trying to debug failures.
I’ve listed and documented some more examples from Dariusz Andrzej Stefański’s post Assertions below over on GitHUb, link is at the top of the page.
Matchers take some getting use to, but over on the Hamcrest site is some great documentation on all the matchers available. And to repeat from the previous lesson, your assertions are really important, so take some time to learn the library, arming yourself to being able to implement the exact assertions you require.