Introduction to Hamcrest Collection Matchers

Another post in the series of Hamcrest Matchers, a framework for writing test matcher objects. This week we’ll dive into collections and iterables, and we’ll see how we can use Hamcrest for making those asserts even more readable.

In many software projects I encounter code like the following:

Or, even worse:

The second loses context by not knowning the expected value and the actual value; it knows only that they are not equal.

So, while this above might be a valid asserts, their readability and error feedback can be improved by using a framework like Hamcrest. This can be done in the following way:

In my opinion, this increases readability quite a bit, and makes it easier to maintain tests like this. Check the following piece of code for more examples:

Error messages

Whenever a assertion fails, you get a pretty clear error message, which will help you quickly solve issues you run into. For example, if in the above code example I would have made a wrong assumption, and instead of:

If would have typed:

The following error message would have shown up:

Whereas the the JUnit equivalent:

Would have resulted in the following:

Which would have helped a great deal also, but it’s just that the Hamcrest one is a bit more clear, and a bit more elaborate on the error message.

I hope this helps in picking up Hamcrest and that it helps in writing clear, consistent tests. See you next week!

4 replies
  1. Alex
    Alex says:

    Hey! Heads up, you have to Override equals for any of this to work. Also heads up. If you want good errors on failed assertions, you should override toString.

  2. Stephen
    Stephen says:

    Is there one that compares all elements of an array or collection to another, even for ones with guaranteed ordering?

Comments are closed.