What are Matchers?

Course Home | Code Example(s)

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 25 c'. Understanding assertions we can get by, we know assert equals is checking they are equal, but it's not explicit in the words. The second example 'assertThat(c, is(equalTo(25)));' reads 'assert that c is equal to 25'. This is much nicer to read in my opinion.

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.

Next Lesson ➔

Resources

Assertions
Matchers and assertThat
Benefits of AssertThat

Richard Bradshaw's photo
Author

Richard Bradshaw

@FriendlyTester

Software Tester, speaker and trainer at Friendly Testing. BossBoss at Ministry of Testing. Whiteboard Testing creator. Striving to improve the testing craft.

Comments