我有两个列表,我想验证它们具有相同顺序的相同对象。出于这个原因我使用hamcrest但由于某种原因我不明白我得到编译错误:
有人可以解释错误以及如何解决它吗?
List<String> actual = Arrays.asList("asd", "bc", "qwe");
List<String> expected = Arrays.asList("asd", "bc", "qwe");
assertThat(actual,IsIterableContainingInAnyOrder.containsInAnyOrder(expected));
这是错误消息:
com.me.Test.java:[160,1] no suitable method found for
assertThat(java.util.List<java.lang.String>,org.hamcrest.Matcher<java.lang.Iterable<?
extends java.util.List<java.lang.String>>>)
method org.junit.Assert.<T>assertThat(T,org.hamcrest.Matcher<T>) is not applicable
(no instance(s) of type variable(s) T exist so that argument type
org.hamcrest.Matcher<java.lang.Iterable<? extends java.util.List<java.lang.String>>> conforms to formal parameter type org.hamcrest.Matcher<T>)
method org.junit.Assert.<T>assertThat(java.lang.String,T,org.hamcrest.Matcher<T>) is not applicable
(cannot instantiate from arguments because actual and formal argument lists differ in length)
答案 0 :(得分:4)
查看javadoc of IsIterableContainingInAnyOrder.containsInAnyOrder
。假设您没有尝试将Matcher
传递给此方法,您应该将数组(或varargs)传递给此方法,例如:
assertThat(actual, IsIterableContainingInAnyOrder.containsInAnyOrder("qwe", "asd", "bc"));
或
assertThat(actual,IsIterableContainingInAnyOrder.containsInAnyOrder(expected.toArray(new String[expected.size()])));
答案 1 :(得分:1)
我只想使用Set,或者先排序数组。
Collectons.sort(actual);
Collections.sort(expected); // if not sorted already.
assertEquals(expected, actual);
或在Java 8中
actual.sort();
expected.sort();
assertEquals(expected, actual);
或者是否可以忽略重复
assertEquals(new HashSet<>(expected), new HashSet<>(actual));