【问题标题】:hamcrest 1.3 hasItems fails test when comparing identical lists比较相同列表时,hamcrest 1.3 hasItems 未通过测试
【发布时间】:2013-08-26 21:04:29
【问题描述】:

尝试比较 2 个列表时,以下行失败:

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;

assertThat(
    actualDealSummary.getDeals(), 
    hasItems(expectedDealSummary.getDeals().toArray(new Deal[expectedDealSummary.getDeals().size()])));

使用 JUnit 4.11 和 hamcrest-all (1.3):

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
</dependency>

我只想检查实际列表是否具有预期列表的值,但出现以下错误:

java.lang.AssertionError: 预期:(包含 &LT;SIXRxrImUE&GT 的集合;以及包含 &LT;RQjVbVRlyG&GT 的集合;以及包含 &LT;avnKxogdyN&GT 的集合;) 但是:包含&LT;SIXRxrImUE&GT的集合;是&LT;SIXRxrImUE&GT;,是&LT;RQjVbVRlyG&GT;,是&LT;avnKxogdyN&GT; 在 org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20) 在 org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8) 在

如何使用 hamcrest 的内置 Matchers 来比较 2 个 pojo 列表?

【问题讨论】:

    标签: junit4 assertions hamcrest


    【解决方案1】:

    您的Deal 类需要实现equals 才能使其工作。您可能会发现检查相等性更简单:

    assertEquals(expectedDealSummary.getDeals(), actualDealSummary.getDeals());
    

    请注意,hasItems 正在执行与此稍有不同的检查,并确认实际列表是预期列表的超集;即使还存在意外项目,这也会导致它通过。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多