【发布时间】:2021-06-25 01:28:36
【问题描述】:
我正在尝试使用断言检查两个集合是否相同。它们应该是相同的,即使它们的元素顺序不同。
这是我检查相等性的方法:
public static <T> void assertCollectionsAreEquals (Collection<T> expected, Collection<T> actual, String message) {
Assertions.assertEquals(expected, actual, message);
}
示例集合:
Collection <Integer> one = new ArrayList<Integer>();
Collection <Integer> two = new ArrayList<Integer>();
Collection <Integer> three = new ArrayList<Integer>();
one.add(1);
one.add(2);
two.add(1);
two.add(2);
three.add(2);
three.add(1);
所以我的收藏看起来像这样:
One:[1, 2]
Two:[1, 2]
Three:[2, 1]
测试:
assertCollectionsAreEquals(one, two, "Not Equals");
assertCollectionsAreEquals(one, three, "Not Equals");
输出:
Exception in thread "main" org.opentest4j.AssertionFailedError: Not Equals ==> expected: <[1, 2]> but was: <[2, 1]>
如何使我的所有测试集合的测试成功?
【问题讨论】:
-
先对集合进行排序,然后进行比较。
-
“它们应该是一样的,即使顺序不同”,那么,
Set的广告是什么? -
equals()的概念没有在层次结构的那个级别定义,可用的定义完全取决于特定集合的合同。您的方法接受任何Collection,但您不能将其应用于List<>和Set<>。在回答问题之前,您需要考虑实际的实现及其行为。 -
您可能需要考虑一个不同的断言库,它具有比 junit 内置的断言集更丰富的断言集。例如在 assertJ 你可以使用
assertThat(one).containsExactlyInAnyOrder(two)
标签: java junit collections assertion