Matching multiple properties in one Matcher

Szympek picture Szympek · Feb 16, 2016 · Viewed 10k times · Source

I need to write Matcher which will check multiple properties. For single property i've used:

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;

    Matcher<Class> matcherName = Matchers.<Class> hasProperty("propertyName",equalTo(expectedValue));

how am I suppose to check more properties in one Matcher ?

Answer

Ruben picture Ruben · Feb 16, 2016

You can check for more properties using one matcher by combining matchers with allOf:

    Matcher<Class> matcherName = allOf(
        hasProperty("propertyName", equalTo(expected1)),
        hasProperty("propertyName2", equalTo(expected2)));

But I guess that what you are actually looking for is the samePropertyValuesAs one, that checks if a bean has the same property values as another one by checking the properties itself instead of the equals method:

    assertThat(yourBean, samePropertyValuesAs(expectedBean));