Creating flexible expressions of intent with Hamcrest

The following paragraphs will introduce the essentials of how to apply Hamcrest matchers to test assertion and show you how to write your own predicate extensions.

Using matcher expressions

Hamcrest, [HAMJAV], aims to provide an API to create flexible expressions of intent. The utility offers nestable predicates called Matchers to do so. These allow writing complex verification conditions in a way which many developers consider easier to read than Boolean operator expressions.

Test assertion is supported by the MatcherAssert class. It offers the assertThat(T, Matcher<? super T>) static helper method. The first argument passed is the object to verify. The second is an appropriate predicate used ...

Get Testing with JUnit now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.