Mockito和Hamcrest:如何验证Collection参数的调用? [英] Mockito and Hamcrest: how to verify invocation of Collection argument?
问题描述
请假设以下界面:
pre> public interface Service {
void perform(Collection< String> elements);
}
以下是测试片段:
Service service = mock(Service.class);
$ b $ //执行业务逻辑
验证(服务).perform(Matchers.argThat(contains(a,b)));
所以我想验证一下我的业务逻辑实际上是用一个包含a和b。
但是,的返回类型包含(...)
为匹配器<可迭代< ;?扩展E>>
,所以 Matchers.argThat(...)
返回 Iterable< String>
在我的情况下,这自然不适用于所需的集合< String>
。
我知道我可以使用参数捕获器,如 Hamcrest hasItem和Mockito验证不一致 ,但我非常想不要。
有任何建议!
Thanks!
您可以写出
<$ p验证(服务).perform((集合< String>)Matchers.argThat(contains(a,b)));
从编译器的角度来看,这是铸造一个 Iterable< String> 到
集合< String>
这很好,因为后者是前者的子类型。在运行时, argThat
将返回 null
,所以可以传递给执行
没有
ClassCastException
。关于它的重要一点是,匹配器进入Mockito的内部验证参数结构,这就是 argThat
所做的。
I'm running into a generics problem with Mockito and Hamcrest.
Please assume the following interface:
public interface Service {
void perform(Collection<String> elements);
}
And the following test snippet:
Service service = mock(Service.class);
// ... perform business logic
verify(service).perform(Matchers.argThat(contains("a", "b")));
So I want to verify that my business logic actually called the service with a collection that contains "a" and "b" in that order.
However, the return type of contains(...)
is Matcher<Iterable<? extends E>>
, so Matchers.argThat(...)
returns Iterable<String>
in my case, which naturally does not apply to the required Collection<String>
.
I know that I could use an argument captor as proposed in Hamcrest hasItem and Mockito verify inconsistency, but I would very much like not to.
Any suggestions! Thanks!
You can just write
verify(service).perform((Collection<String>) Matchers.argThat(contains("a", "b")));
From the compiler's point of view, this is casting an Iterable<String>
to a Collection<String>
which is fine, because the latter is a subtype of the former. At run time, argThat
will return null
, so that can be passed to perform
without a ClassCastException
. The important point about it is that the matcher gets onto Mockito's internal structure of arguments for verification, which is what argThat
does.
这篇关于Mockito和Hamcrest:如何验证Collection参数的调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!