【问题标题】:How to use hamcrest contains to compare 2 lists?如何使用 hamcrest 包含比较 2 个列表?
【发布时间】:2016-03-14 18:32:55
【问题描述】:

为什么这个测试失败了?当您传入以逗号分隔的单个字符串时,我知道 contains 有效,但我想看看是否可以只传入整个字符串列表。我只是想确保列表 1 包含列表 2 的所有内容。

@Test
public void testContains() {
    String expected1 = "hello";
    String expected2 = "goodbye";
    List<String> expectedStrings = new ArrayList<>();
    expectedStrings.add(expected1);
    expectedStrings.add(expected2);
    List<String> actualStrings = new ArrayList<>();
    actualStrings.add(expected1);
    actualStrings.add(expected2);
    assertThat(actualStrings, contains(expectedStrings));
}

使用此断言是否可以接受?

assertThat(actualStrings, is(expectedStrings));

【问题讨论】:

  • containsAll 而不是包含。检查API
  • @RahulSharma 所以你会像assertThat(actualStrings.containsAll(expectedStrings), is(true))一样使用它?
  • @RahulSharma 我正在寻找更多类似于 List 方法 containsAll 的 hamcrest 匹配器,所以我可以这样做:assertThat(actualStrings, containsAll(expectedStrings))。我认为它比 is(true) 匹配器读起来更好。
  • 我真的不知道如何用 hamcrest 做到这一点。我在测试中使用 JUnit 断言。 JUnit 具有大部分 hamcrest 功能,如果在您的情况下使用 hamcrest 不是强制性的,我建议使用 JUnit。
  • @RahulSharma 好的,那么在这种情况下,您的 JUnit 断言会是什么样子?

标签: java junit hamcrest


【解决方案1】:

没有采用预期值列表的重载 contains 方法。

在声明中assertThat(actualStrings, contains(expectedStrings)) 调用以下方法(在Matchers 类中):

<E> org.hamcrest.Matcher<java.lang.Iterable<? extends E>> contains(E... items)

基本上你是说你期望一个包含一个元素的列表,这个元素是expectedStrings,但实际上它是expected1E 的类型是List&lt;String&gt;,而不是String)。要验证,请将以下内容添加到应该通过的测试中:

List<List<String>> listOfactualStrings = new ArrayList<>();
listOfactualStrings.add(actualStrings);
assertThat(listOfactualStrings, contains(expectedStrings));

要使断言起作用,您必须将列表转换为数组:

assertThat(actualStrings, contains(expectedStrings.toArray()));

【讨论】:

    【解决方案2】:

    如果您想为列表中的每个项目应用匹配器,您可以使用everyItem 匹配器,如下所示:

    everyItem(not(isEmptyOrNullString()))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 1970-01-01
      • 2019-11-03
      相关资源
      最近更新 更多