java - 测试 List<List<T>> 包含任何顺序的相同项目

标签 java junit hamcrest

我想比较两个 List<List<String>>以任何顺序包含相同的元素。它们不相等。

// expectedResult 
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

另一个是

// result
[
  ["eat", "tea", "ate"], 
  ["bat"], 
  ["tan", "nat"]
]

我应该使用什么测试方法(来自哪些库)来比较 **elements 中的元素而不进行排序?**

我试过了,没有成功。

import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertThat;

assertThat(expectedResult, containsInAnyOrder(result));

最佳答案

你可以尝试使用 Apache Commons

public static boolean isEqualCollection(Collection a, Collection b)

Returns true iff the given Collections contain exactly the same elements with exactly the same cardinalities.

That is, iff the cardinality of e in a is equal to the cardinality of e in b, for each element e in a or b.

Parameters:

  • a - the first collection, must not be null
  • b - the second collection, must not be null

Returns: true iff the collections contain the same elements with the same cardinalities.

import org.apache.commons.collections4.CollectionUtils;
import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

public class TestSO {

    @Test
    public void testLists() {
        List<List<String>> list = Arrays.asList(Arrays.asList("ate", "eat", "tea"), Arrays.asList("nat", "tan"), Arrays.asList("bat"));
        List<List<String>> sameList = Arrays.asList(Arrays.asList("ate", "eat", "tea"), Arrays.asList("bat"), Arrays.asList("nat", "tan"));
        List<List<String>> differentList = Arrays.asList(Arrays.asList("ate", "eat"), Arrays.asList("bat"), Arrays.asList("nat", "tan"));

        Assert.assertTrue(CollectionUtils.isEqualCollection(list, sameList));
        Assert.assertFalse(CollectionUtils.isEqualCollection(list, differentList));
    }

}

关于java - 测试 List<List<T>> 包含任何顺序的相同项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57878641/

相关文章:

java - 隐藏 BIRTH 中的网格/表格,没有来自数据源的结果

java - 在框架布局中显示 map fragment

intellij-idea - Junit 无法在 Play 中处理 SBT! Intellij 14 上的框架项目

java - 在没有 ArgumentCaptor 的情况下匹配可变对象

testing - 如何使用 hamcrest 断言对象相等

java - 使用自定义字段中的特定条件断言预期异常

java - 使用串行通信在微 Controller 上写入数据时出现问题

java - 返回所有 HtmlPage 的 HTML

java - Mockito - 没有为其中一个测试用例注入(inject)模拟

java - @Before 没有为 @Test 实例化我的对象