hamcrest hasItem and hasProperty, assert if a object with property value exists
Asked Answered
V

2

36
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.equalTo;

assertThat(actual, hasItem(hasProperty("id", equalTo(1L))));

where actual is a POJO with id as Long.

I get,

The method assertThat(T, Matcher<? super T>) in the type MatcherAssert is not applicable for the arguments (List, Matcher<Iterable<? super Object>>)

From various documentation and other stackoverflow pages, it should be valid, but I get the above error.

Ventris answered 20/11, 2013 at 18:11 Comment(1)
Please see "How to Ask" and the linked pages and "minimal reproducible example". What is the minimal code that demonstrates the problem you encountered, along with the explanation of the problem, and the minimal input data and the expected result? We need to be able to duplicate the problem, and this example code won't do that.Push
C
65

Try explicitly filling in the type parameter - assuming actual is a List<YourPojo>, try calling:

assertThat(actual, hasItem(Matchers.<YourPojo>hasProperty("id", equalTo(1L))));
Countermeasure answered 20/11, 2013 at 18:23 Comment(1)
thanks, that works. We had a similar issue when using containsInAnyOrder but couldn't get it to work.Ventris
P
13

The shorter version when you do not have to specify class type:

List<IssueDefinitionDto> definitions = ...; // Tested variable
...
assertThat(definitions, hasItem(hasProperty("id", is(10L))));
Pinky answered 25/11, 2016 at 16:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.