Hamcrest Assertions

Learn about the use of Hamcrest assertions and some common matchers in writing Unit Tests.

In the last chapter, we learned that Hamcrest (an anagram of the word matchers) is a newer, more expressive framework for writing matcher objects that allow match rules to be defined declaratively. It supports customized assertion matches.

Now, let’s learn more about Hamcrest and learn about its code implementation.

Hamcrest assertion arguments

  • The first argument in a Hamcrest assertion is the actual expression—the value we want to verify (often a method call to the underlying system).
  • The second argument is a matcher. A matcher is a static method call that allows us to compare the results of an expression against an actual value.

Matchers

The Hamcrest CoreMatchers class that ships with JUnit provide us with a solid starter set of matchers. Although it is possible to use only a few matchers, our tests will be more expressive if we use more matchers. This section presents a few key Hamcrest matches.

Matchers can impart greater readability to our tests as they read fairly well left-to-right. For example, we can quickly paraphrase the assertion given ...