I have a method that will return a list of objects of type MyClass
. MyClass
has many properties, but I care about type
and count
. I want to write a test that asserts that the returned list contains at least one element that matches a certain condition. For instance, I want at least one element in the list of type "Foo"
and count 1
.
I'm trying to figure out how to do this without literally looping over the returned list and checking each element individually, breaking if I find one that passes, like:
boolean passes = false;
for (MyClass obj:objects){
if (obj.getName() == "Foo" && obj.getCount() == 1){
passes = true;
}
}
assertTrue(passes);
I really don't like this structure. I'm wondering if there's a better way to do it using assertThat
and some Matcher.
with hamcrest imports
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
you can test with
assertThat(foos, hasItem(allOf(
hasProperty("name", is("foo")),
hasProperty("count", is(1))
)));