hamcrest 1.3 hasItems在比较相同列表时失败测试

时间:2013-08-26 21:04:30

标签: junit4 assertions hamcrest

尝试比较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: 
Expected: (a collection containing <SIXRxrImUE> and a collection containing <RQjVbVRlyG> and a collection containing <avnKxogdyN>)
     but: a collection containing <SIXRxrImUE> was <SIXRxrImUE>, was <RQjVbVRlyG>, was <avnKxogdyN>
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:8)
    at 


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

1 个答案:

答案 0 :(得分:0)

您的Deal课程需要实施equals才能实现此目的。您可能会发现检查相等性更简单:

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

请注意,hasItems对此进行了略微不同的检查,并确认实际列表是预期列表的超集;即使意外物品也存在,这也会导致它通过。