Search code examples
javahamcrest

Assert Property from List


I have a the following code which I can not figure out why it is not working:

@Test
public void someTest(){

    List<MyItem> i = new ArrayList<>();
    MyItem i1 = new MyItem();
    i1.setName("paul");
    MyItem i2 = new MyItem();
    i2.setName("detlef");
    i.add(i1);
    i.add(i2);

    MatcherAssert.assertThat(i,
            Matchers.contains(
                    HasPropertyWithValue.hasProperty("name", CoreMatchers.is("paul"))));

}

MyItem:

public class MyItem {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }
}

I found the solution here but my unit test will give an AssertionError:

java.lang.AssertionError: 
Expected: iterable containing [hasProperty("name", is "paul")]
     but: Not matched: <MyItem@4e08711f>
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)
    at TestHarnes.someTest(TestHarnes.java:115)

Appretiate any help or hint


Solution

  • I think contains matches all of your items in the list, but your asserting only one item. You need to check for both items or use another matcher, for instance hasItems.