hamcrest hasItem和hasProperty,断言是否存在具有属性值的对象

wen*_*nic 28 java unit-testing hamcrest

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))));
Run Code Online (Sandbox Code Playgroud)

其中,实际是一个ID为Long的POJO.

我明白了

assertThat(T, Matcher<? super T>)类型中的方法MatcherAssert不适用于参数(List<Pojo>, Matcher<Iterable<? super Object>>)

从各种文档和其他stackoverflow页面,它应该是有效的,但我得到上述错误.

pob*_*key 54

尝试显式填写类型参数 - 假设actual是a List<YourPojo>,尝试调用:

assertThat(actual, hasItem(Matchers.<YourPojo>hasProperty("id", equalTo(1L))));
Run Code Online (Sandbox Code Playgroud)


Cyv*_*yva 8

您不必指定类类型时的较短版本:

List<IssueDefinitionDto> definitions = ...; // Tested variable
...
assertThat(definitions, hasItem(hasProperty("id", is(10L))));
Run Code Online (Sandbox Code Playgroud)