This library provides Hamcrest matchers to easily build composite matchers for objects. For example:
public static Matcher<Person> personEqualTo(Person expected) {
return compose("a person with", hasFeature("title", Person::getTitle, equalTo(expected.getTitle())))
.and(hasFeature("first name", Person::getFirstName, equalTo(expected.getFirstName())))
.and(hasFeature("last name", Person::getLastName, equalTo(expected.getLastName())));
}
See the demo module to run this example. The PersonMatchersTest test case defines the behaviour of this matcher.
Hamcrest Compose is available in the Maven Central repository. Start by adding a dependency to your Maven project:
<dependency>
<groupId>org.hobsoft.hamcrest</groupId>
<artifactId>hamcrest-compose</artifactId>
<version>0.1.0</version>
<scope>test</scope>
</dependency>
Hamcrest Compose provides two matchers:
This factory method builds a composite matcher that logically ANDs a number of other matchers. For example:
assertThat("ham", compose(startsWith("h")).and(containsString("a")).and(endsWith("m")));
This differs from Hamcrest's composite matchers allOf and both in the following ways:
- It does not short circuit. This means that all mismatches are reported, not just the first one.
- It does not describe itself using parenthesis. This produces more readable descriptions.
- It supports an optional description to help describe the composition
- It does not repeat the matcher's description when describing a mismatch
This factory method builds a matcher that matches a 'feature' of an object. A feature is any value that can be obtained from the object by a Function. Typically this is a lambda such as a method reference, for example:
assertThat(person, hasFeature(Person::getFirstName, equalTo("ham")));
By default this matcher will describe itself and any mismatches by using the toString
method of the feature function. When using lambdas this is not particularly informative so a feature description can be specified:
assertThat(person, hasFeature("a person with first name", Person::getFirstName, equalTo("ham")));
This feature description is also used to describe any mismatches. To specify a feature name for the mismatch only:
assertThat(person, hasFeature("a person with first name", "first name", Person::getFirstName, equalTo("ham")));