Hamcrest比较收藏品 [英] Hamcrest compare collections
问题描述
我正在尝试比较2个列表:
I'm trying to compare 2 lists:
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)
我该如何写呢?
推荐答案
如果你想要断言两个列表是相同的,不要使用Hamcrest复杂化:
If you want to assert that the two lists are identical, don't complicate things with Hamcrest:
assertEquals(expectedList, actual.getList());
如果您真的打算执行不区分大小写的比较,可以调用 containsInAnyOrder
varargs方法并直接提供值:
If you really intend to perform an order-insensitive comparison, you can call the containsInAnyOrder
varargs method and provide values directly:
assertThat(actual.getList(), containsInAnyOrder("item1", "item2"));
(假设您的清单是 String
,而不是代理商
,对于这个例子。)
(Assuming that your list is of String
, rather than Agent
, for this example.)
如果你真的想用内容调用相同的方法一个列表
:
If you really want to call that same method with the contents of a List
:
assertThat(actual.getList(), containsInAnyOrder(expectedList.toArray(new String[expectedList.size()]));
没有这个,你'用一个参数调用方法并创建一个 Matcher
,它希望匹配 Iterable
其中每个元素是列表
。这不能用于匹配列表
。
Without this, you're calling the method with a single argument and creating a Matcher
that expects to match an Iterable
where each element is a List
. This can't be used to match a List
.
也就是说,您无法将列表< Agent>
与匹配< Iterable< List< ;代理>>
,这是您的代码尝试的内容。
That is, you can't match a List<Agent>
with a Matcher<Iterable<List<Agent>>
, which is what your code is attempting.
这篇关于Hamcrest比较收藏品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!