Search code examples
javaspring-bootmatcherhamcrest

Hamcrest. Match item in collection with 2 specific property values


I have a test with a collection of SpecialObject as result. SpecialObject has "name" and "surname" as properties. I want to test if the collection contains a specialObject with 2 specific properties, "name=myname" and "surname=lastname".

Here is what I have tried without success:

assertThat(result, Matchers.<SpecialObject>hasItem(
    allOf(
          hasProperty("name", equalTo("myname")),
          hasProperty("surname", equalTo("lastname"))
));

Solution

  • You can use both matcher to check if both properties has excepcted values.

        Assert.assertThat(result, Matchers.<SpecialObject>hasItem(
                Matchers.both(hasProperty("name", equalTo("myname")))
                        .and(hasProperty("surname", equalTo("lastname")))));