【问题标题】:How do Hamcrest's hasItems, contains and containsInAnyOrder differ?Hamcrest 的 hasItems、contains 和 containsInAnyOrder 有何不同?
【发布时间】:2015-11-21 06:41:37
【问题描述】:

Hamcrest 提供了许多匹配器来断言集合的内容。所有这些情况都通过了:

Collection<String> c = ImmutableList.of("one", "two", "three");
assertThat(c, hasItems("one", "two", "three");
assertThat(c, contains("one", "two", "three");
assertThat(c, containsInAnyOrder("one", "two", "three");

hasItemscontainscontainsInAnyOrder 有何不同?

【问题讨论】:

    标签: hamcrest


    【解决方案1】:

    hasItems checks:

    连续通过检查的 Iterable 产生至少一项与指定 items 中的对应项相等的项。

    也就是说,它确保集合至少包含这些项目,以任何顺序。所以,

    assertThat(c, hasItems("one", "two"));
    

    也会通过,忽略多余的项目。并且:

    assertThat(c, hasItems("three", "two", "one"));
    

    也会通过。

    contains checks:

    对检查过的Iterable 进行一次遍历会产生一系列项目,每个项目在逻辑上等于指定项目中的相应项目。对于正匹配,检查的可迭代对象的长度必须与指定项的数量相同。

    所以它确保集合准确地包含这些项目:

    assertThat(c, contains("one", "two")); // Fails
    

    这会失败,因为剩余的 "three" 不匹配。

    assertThat(c, contains("three", "two", "one")); // Fails
    

    这会失败,因为对应的项目不匹配。

    另一个相关的匹配器,containsInAnyOrderchecks,这些项目确实存在,但顺序不限:

    Iterables 创建一个与顺序无关的匹配器,当通过检查的Iterable 产生一系列项目时匹配,每个项目在逻辑上等于指定项目中任意位置的一个项目。

    缺少项目的测试失败:

    assertThat(c, containsInAnyOrder("one", "two")); // Fails
    

    但是顺序不同的所有项目都会通过:

    assertThat(c, containsInAnyOrder("three", "two", "one"));
    

    【讨论】:

    • 我会将 contains 重命名为 containsOf
    • contains 是一个巨大的误称。我原以为containsCollection#contains 一样。
    • AssertJ 调用此方法containsExactly,这也可能有助于减少意外。
    • 如果我想使用 containsInAnyOrder,但列表包含重复项怎么办?例如,我想检查 List 是否包含确切的元素,但它们有重复 - 在这种情况下 containsAnyOrder("three","three","one") 将成立,即使测试的列表只有 ("three,"one ") 元素。如何处理?
    • @DaneelS.Yaitskov containsOfOrdered
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多