【问题标题】:hamcrest hasItem and hasProperty, assert if a object with property value existshamcrest hasItem 和 hasProperty,断言是否存在具有属性值的对象
【发布时间】:2013-11-20 18:11:23
【问题描述】:
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))));

其中actual 是一个ID 为Long 的POJO。

我明白了,

类型中的方法assertThat(T, Matcher super T>) MatcherAssert 不适用于参数(列表, 匹配器>)

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

【问题讨论】:

  • 请参阅“How to Ask”以及链接页面和“minimal reproducible example”。演示您遇到的问题的最少代码是什么,以及问题的解释,以及最少的输入数据和预期结果?我们需要能够复制问题,而这个示例代码不会这样做。

标签: java unit-testing hamcrest


【解决方案1】:

尝试显式填写类型参数——假设actualList<YourPojo>,尝试调用:

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

【讨论】:

  • 谢谢,这行得通。我们在使用 containsInAnyOrder 时遇到了类似的问题,但无法正常工作。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2013-10-18
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-09
    • 2012-02-02
    相关资源
    最近更新 更多