首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >滥用hamcrest hasItems

滥用hamcrest hasItems
EN

Stack Overflow用户
提问于 2013-02-18 16:45:29
回答 1查看 2.6K关注 0票数 10

我有一个整数列表(current),我想检查这个列表是否包含list expected中的所有元素,而不包含list notExpected中的一个元素,因此代码如下所示:

代码语言:javascript
复制
    List<Integer> expected= new ArrayList<Integer>();
    expected.add(1);
    expected.add(2);

    List<Integer> notExpected = new ArrayList<Integer>();
    notExpected.add(3);
    notExpected.add(4);

    List<Integer> current = new ArrayList<Integer>();
    current.add(1);
    current.add(2);


    assertThat(current, not(hasItems(notExpected.toArray(new Integer[expected.size()]))));

    assertThat(current, (hasItems(expected.toArray(new Integer[expected.size()]))));

再见,再见,真好。但当我添加

代码语言:javascript
复制
    current.add(3);

测试也是绿色的。我是不是误用了汉姆克雷斯特火柴盒?顺便说一句。

代码语言:javascript
复制
    for (Integer i : notExpected)
        assertThat(current, not(hasItem(i)));

给了我正确的答案,但我认为我可以很容易地使用hamcrest matcher来解决这个问题。我使用的是junit 4.11和hamcrest 1.3

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-18 17:52:44

只有当来自hasItems(notExpected...)的所有元素都在current中时,notExpected才会与current匹配。所以有了这条线

代码语言:javascript
复制
assertThat(current, not(hasItems(notExpected...)));

您断言current不包含来自notExpected的所有元素。

断言current不包含任何来自notExpected的元素的一种解决方案

代码语言:javascript
复制
assertThat(current, everyItem(not(isIn(notExpected))));

然后,您甚至不必将列表转换为数组。这个变体可能更具可读性,但需要转换为数组:

代码语言:javascript
复制
assertThat(current, everyItem(not(isOneOf(notExpected...))));

请注意,这些匹配器不是来自hamcrest-core中的CoreMatchers,因此您需要添加对hamcrest-library的依赖。

代码语言:javascript
复制
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
</dependency>
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14932363

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档