Java hamcrest hasItem 和 hasProperty,断言是否存在具有属性值的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20103640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
hamcrest hasItem and hasProperty, assert if a object with property value exists
提问by wenic
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.
其中 actual 是一个 ID 为 Long 的 POJO。
I get,
我明白了,
The method assertThat(T, Matcher<? super T>)
in the type MatcherAssert
is not applicable for the arguments (List<Pojo>, Matcher<Iterable<? super Object>>)
assertThat(T, Matcher<? super T>)
类型中的方法MatcherAssert
不适用于参数(List<Pojo>, Matcher<Iterable<? super Object>>)
From various documentation and other stackoverflow pages, it should be valid, but I get the above error.
从各种文档和其他 stackoverflow 页面来看,它应该是有效的,但我收到了上述错误。
采纳答案by pobrelkey
Try explicitly filling in the type parameter - assuming actual
is a List<YourPojo>
, try calling:
尝试明确填写类型参数 - 假设actual
是 a List<YourPojo>
,尝试调用:
assertThat(actual, hasItem(Matchers.<YourPojo>hasProperty("id", equalTo(1L))));
回答by Cyva
The shorter version when you do not have to specify class type:
不必指定类类型时的较短版本:
List<IssueDefinitionDto> definitions = ...; // Tested variable
...
assertThat(definitions, hasItem(hasProperty("id", is(10L))));