Introduction to Hamcrest Core Matchers

In our previous post, we got a small introduction into Hamcrest, a framework for writing test matcher objects, and why you should use them. This post will dive deeper into Hamcrest Matchers. A Matcher is a ‘match’ rule to be defined declaratively. The Hamcrest library comes with numerous matchers included, and it’s of course possible to write your own Matcher.

The topic of this week: the Core Matchers.

The common Matchers of Hamcrest are the following:
is, equalTo, not, anything, instanceOf, any, isA, nullValue, notNullValue, sameInstance, theInstance, isIn, isOneOf and hasToString.

I will give an example of all of them in the code block below:

As you can see, the Hamcrest assertions are very readable, and makes your testcode a bit easier to maintain.

PS: I always wanted to write some posts about Hamcrest, but the thing which really triggered me was the Hamcrest cheat sheet created by Marc Philipp. Be sure to check it out, it’s a great piece of work!