汉克雷斯特比较系列

2022-08-31 08:07:37

我试图比较2个列表:

assertThat(actual.getList(), is(Matchers.containsInAnyOrder(expectedList)));

但想法

java: no suitable method found for assertThat(java.util.List<Agent>,org.hamcrest.Matcher<java.lang.Iterable<? extends model.Agents>>)
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 model.Agents>> 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)

我应该怎么写?


答案 1

如果你想断言这两个列表是相同的,不要用Hamcrest使事情复杂化:

assertEquals(expectedList, actual.getList());

如果您真的打算执行不区分顺序的比较,则可以调用 varargs 方法并直接提供值:containsInAnyOrder

assertThat(actual.getList(), containsInAnyOrder("item1", "item2"));

(在本例中,假设您的列表是 的,而不是 。StringAgent

如果您真的想使用以下内容调用相同的方法:List

assertThat(actual.getList(), containsInAnyOrder(expectedList.toArray(new String[expectedList.size()]));

如果没有这个,您将使用单个参数调用该方法,并创建一个期望与每个元素都是 .这不能用于匹配 .MatcherIterableListList

也就是说,您不能将 a 与 匹配,而 这正是您的代码正在尝试的。List<Agent>Matcher<Iterable<List<Agent>>


答案 2
List<Long> actual = Arrays.asList(1L, 2L);
List<Long> expected = Arrays.asList(2L, 1L);
assertThat(actual, containsInAnyOrder(expected.toArray()));

@Joe答案的较短版本,没有多余的参数。


推荐