Hamcrest 比较集合 [英] Hamcrest compare collections

查看:19
本文介绍了Hamcrest 比较集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较 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,而不是 Agent,在本例中.)

(Assuming that your list is of String, rather than Agent, for this example.)

如果你真的想用 List 的内容调用相同的方法:

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 其中 每个元素是一个 List.这不能用于匹配 List.

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.

也就是说,您不能将 ListMatcher> 匹配,这正是您的代码所尝试的.

That is, you can't match a List<Agent> with a Matcher<Iterable<List<Agent>>, which is what your code is attempting.

这篇关于Hamcrest 比较集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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