Junit: assert that a list contains at least one property that matches some condition

ewok :

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.

user2718281 :

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))
    )));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=93831&siteId=1