Search code examples
javaunit-testingjunit4hamcrest

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


Assume I want to unit test a method with this signature:

List<MyItem> getMyItems();

Assume MyItem is a Pojo that has many properties, one of which is "name", accessed via getName().

All I care about verifying is that the List<MyItem>, or any Iterable, contains two MyItem instances, whose "name" properties have the values "foo" and "bar". If any other properties don't match, I don't really care for the purposes of this test. If the names match, it's a successful test.

I would like it to be one-liner if possible. Here is some "pseudo-syntax" of the kind of thing I would like to do.

assert(listEntriesMatchInAnyOrder(myClass.getMyItems(), property("name"), new String[]{"foo", "bar"});

Would Hamcrest be good for this type of thing? If so, what exactly would be the hamcrest version of my pseudo-syntax above?


Solution

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