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

32,168

Solution 1

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

assertThat(actual, hasItem(Matchers.<YourPojo>hasProperty("id", equalTo(1L))));

Solution 2

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

List<IssueDefinitionDto> definitions = ...; // Tested variable
...
assertThat(definitions, hasItem(hasProperty("id", is(10L))));
Share:
32,168
wenic
Author by

wenic

Updated on February 20, 2022

Comments

  • wenic
    wenic about 2 years
    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.