Hamcrest Matchers in JUnit tests

With JUnit being the dominant Test framework, chances are high that during your career as a software engineer, you’ve encountered the JUnit framework in one or more projects. Therefor, code like this:

Should not be unfamiliar to you. This blogpost is on improving the example above. There are good alternatives in writing your tests, like Spock, but these take a little more effort to setup, since it’s mostly used in Groovy projects. The goal of this blogpost is to improve the above Java test with little effort, and for that, we’re going to use Hamcrest.

Hamcrest is (in our case) a set of Java matchers which improve the readability of the code and error messages shown when assertions do not match. So, let’s get back to our original example: what does it really say?

Means something like: verify that the getValue method of result should return the String hello, and if not, print the message ‘result doesn’t match hello’. Wouldn’t it be more understandable if we could write something like this in a more natural language? Well, with Hamcrest we can:

In this example, we’re using ‘assertThat’, which is a method coming from JUnit. JUnit itself supports a random amount of Matchers, but I would recommend on forgetting those, and just use only the Matchers from Hamcrest itself (which means, adding the Hamcrest library to the project, version 1.3 at this moment), since the Hamcrest library contains a much bigger set of Matchers. Also, note that the ‘is’ method here is optional, but I added it to improve readability.

Hamcrest can be added to your Maven project by including the following dependency:

And using this library, you’ll get many matchers, supporting String, Collections, Maps, Numbers, and even XML elements, but more on that in my next blog!

One last note: be aware to use the latests version of JUnit though (currently 4.11). When using an older version you might (read: will) run into dependency issues. Don’t say I didn’t warn you!

2 replies

Comments are closed.