如何使用 hamcrest 包含比较 2 个列表?

How to use hamcrest contains to compare 2 lists?

为什么这个测试失败了?我知道 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));

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

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

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

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

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

要使断言有效,您必须将列表转换为数组:

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

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

everyItem(not(isEmptyOrNullString()))