AssertEquals 2 列表忽略顺序 [英] AssertEquals 2 Lists ignore order

查看:51
本文介绍了AssertEquals 2 列表忽略顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信这应该是一个非常简单的问题.但不知何故,我无法在 Google 中找到答案.

That should be really simple question I believe. But somehow I can't find answer in Google.

假设我有 2 个字符串列表.第一个包含字符串A"和字符串B",第二个包含字符串B"和字符串A"(注意顺序不同).我想用 JUnit 测试它们以检查它们是否包含完全相同的字符串.

Assume that I have 2 Lists of Strings. First contains "String A" and "String B", second one contains "String B" and "String A" (notice difference in order). I want to test them with JUnit to check whether they contains exactly the same Strings.

是否有任何断言检查忽略顺序的字符串的相等性?对于给定的示例 org.junit.Assert.assertEquals 抛出 AssertionError

Is there any assert that checks equality of Strings that ignore order? For given example org.junit.Assert.assertEquals throws AssertionError

java.lang.AssertionError: expected:<[String A, String B]> but was:<[String B, String A]>

解决方法是首先对列表进行排序,然后将它们传递给断言.但我希望我的代码尽可能简单和干净.

Work around is to sort Lists firstly and then pass them to assertion. But I want my code to be as simple and clean as possible.

我使用 Hamcrest 1.3JUnit 4.11Mockito 1.9.5.

推荐答案

正如你提到的,你使用了 Hamcrest,
所以我会选择Matchers系列之一

As you mention that you use Hamcrest,
So I would pick one of the collection Matchers

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

public class CompareListTest {

    @Test
    public void compareList() {
        List<String> expected = Arrays.asList("String A", "String B");
        List<String> actual = Arrays.asList("String B", "String A");
        
        assertThat("List equality without order", 
            actual, containsInAnyOrder(expected.toArray()));
    }
    
}

这篇关于AssertEquals 2 列表忽略顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆