Reputation: 1361
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
Upvotes: 2
Views: 735
Reputation: 24520
If you only want to assert a single item of the list then you need the hasItem
matcher. The contains
matcher checks all items of a list.
assertThat(i, hasItem(hasProperty("name", is("paul"))));
Upvotes: 1
Reputation: 77
IMHO you should test it this way:
MatcherAssert.assertThat(ACTUAL,is(equalTo(EXPECTED)));
You can check size of the list,get object from the list you want and check if it is equalTo expect data. is
and equalTo
you should import as static
Upvotes: 0
Reputation: 2217
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.
Upvotes: 1