我相信这应该是一个非常简单的问题。但不知何故我无法在谷歌中找到答案。
假设我有 2 个字符串列表。首先包含“字符串A”和“字符串B”,第二个包含“字符串B”和“字符串A”(注意顺序差异)。我想测试它们JUnit检查它们是否包含一模一样字符串。
是否有任何断言可以检查忽略顺序的字符串的相等性?对于给定的示例 org.junit.Assert.assertEquals 抛出 AssertionError
java.lang.AssertionError: expected:<[String A, String B]> but was:<[String B, String A]>
解决方法是首先对列表进行排序,然后将它们传递给断言。但我希望我的代码尽可能简单和干净。
I use 汉克雷斯特 1.3, JUnit 4.11, 莫基托 1.9.5.
正如你提到的,你使用Hamcrest http://hamcrest.org/,
所以我会选择 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()));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)