How do I assert an Iterable contains elements with a certain property? How do I assert an Iterable contains elements with a certain property? java java

How do I assert an Iterable contains elements with a certain property?


Thank you @Razvan who pointed me in the right direction. I was able to get it in one line and I successfully hunted down the imports for Hamcrest 1.3.

the imports:

import static org.hamcrest.CoreMatchers.is;import static org.hamcrest.Matchers.contains;import static org.hamcrest.MatcherAssert.assertThat;import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;

the code:

assertThat( myClass.getMyItems(), contains(    hasProperty("name", is("foo")),     hasProperty("name", is("bar"))));


Try:

assertThat(myClass.getMyItems(),                          hasItem(hasProperty("YourProperty", is("YourValue"))));


Its not especially Hamcrest, but I think it worth to mention here. What I use quite often in Java8 is something like:

assertTrue(myClass.getMyItems().stream().anyMatch(item -> "foo".equals(item.getName())));

(Edited to Rodrigo Manyari's slight improvement. It's a little less verbose. See comments.)

It may be a little bit harder to read, but I like the type and refactoring safety.Its also cool for testing multiple bean properties in combination. e.g. with a java-like && expression in the filter lambda.