Hamcrest Assertions
Explore Hamcrest assertions in JUnit to write clearer and more expressive unit tests. Understand how matchers like equalTo and startsWith improve readability and provide better failure diagnostics. Learn to apply Hamcrest's collection and object matchers for more robust test validation.
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
Hamcrestassertion 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 ...