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 Matcher
s 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 to evaluate the first one:
assertThat( item.getTimeStamp(), equalTo( 10L ) );
Matcher implementations provide static factory methods for instantiation (above IsEqual.equalTo(T)
). The intention is to mimic the flow of a natural language. This is...