我遇到了 Mockito 和 Hamcrest 的泛型问题。
请假定以下界面:
public interface Service {
void perform(Collection<String> elements);
}
以及以下测试片段:
Service service = mock(Service.class);
// ... perform business logic
verify(service).perform(Matchers.argThat(contains("a", "b")));
因此,我想验证我的业务逻辑是否确实使用按顺序包含“a”和“b”的集合调用了服务。
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>
。
我知道我可以使用 Hamcrest hasItem 和 Mockito verify inconsistency 中提出的参数捕获器,但我非常不想这样做。
有什么建议么!谢谢!
原文由 Philipp Jardas 发布,翻译遵循 CC BY-SA 4.0 许可协议
你可以只写
从编译器的角度来看,这是将
Iterable<String>
转换为Collection<String>
这很好,因为后者是前者的子类型。 At run time,argThat
will returnnull
, so that can be passed toperform
without aClassCastException
.关于它的重要一点是匹配器进入 Mockito 的内部参数结构以进行验证,这就是argThat
所做的。