java Junit:如何检查两个集合是否相等,元素的顺序不同?

woobm2wo  于 2023-02-18  发布在  Java
关注(0)|答案(3)|浏览(142)

我尝试使用Assert来检查两个集合是否相同。它们应该是相同的,即使它们的元素顺序不同。
下面是我检查等式的方法:

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]>

如何使所有测试集合的测试都成功?

6ovsh4lw

6ovsh4lw1#

在JUnit 5中没有现成的Assert方法来实现这一点,您可以使用Hamcrest来代替:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;

assertThat("Not Equals", one, containsInAnyOrder(two.toArray()));
assertThat("Not Equals", one, containsInAnyOrder(three.toArray()));
4si2a6ki

4si2a6ki2#

assertTrue(one.containsAll(two));
assertTrue(two.containsAll(one));
assertTrue(one.containsAll(three));
assertTrue(three.containsAll(one));
assertTrue(two.containsAll(three));
assertTrue(three.containsAll(two));
5n0oy7gb

5n0oy7gb3#

为了检查两个集合的相等性,应该比较两个集合的大小,接下来可以通过从集合c1的副本中移除集合c2中的元素来计算差,并且如果集合c2为空,则集合相等:

public static <T> boolean areCollectionsEqual(Collection<T> c1, Collection<T> c2) {
    if (c1 == c2) return true;
    
    if (c1 == null || c2 == null || c1.size() != c2.size()) {
        return false;
    }
    
    Collection<T> tmp = new ArrayList<>(c1);
    for (T item : c2) {
        if (!tmp.remove(item)) {
            return false;
        }
    }
    
    return tmp.isEmpty();
}

这种方法允许比较不同类型的集合(例如ListSet
则可在测试中使用常见的assertTrue/assertFalse

public static <T> void assertCollectionsAreEqual(Collection<T> expected, Collection<T> actual, String message) {
    Assertions.assertTrue(areCollectionsEqual(expected, actual), message);    
}

public static <T> void assertCollectionsAreNotEqual(Collection<T> expected, Collection<T> actual, String message) {
    Assertions.assertFalse(areCollectionsEqual(expected, actual), message);    
}
  • Update* Collection::removeAll在集合中包含相同元素但频率不同的情况下可能会产生不正确的结果,例如List.of (1, 2, 2, 2)List.of (1, 2, 1, 2),因此将其替换为迭代remove

相关问题