我想比较两个 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/