Kevin Pauli Kevin Pauli - 10 months ago 49
Java Question

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

is a Pojo that has many properties, one of which is
, accessed via

All I care about verifying is that the
, or any
, contains two
instances, whose
properties have the values
. 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?

Answer Source

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