hasItem和Mockito验证不一致

hasItem和Mockito验证不一致

本文介绍了Hamcrest hasItem和Mockito验证不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了有关Hamcrest和Mockito的问题.这是我想要做的:

I've ran into an issue with hamcrest and mockito.Here is what I'm trying to do:

public class A{
     public void foo(List<B> arg){
          return;
     }
}

public BMatcher extends BaseMatcher<B>{
 //Some impl...
}

在测试中,我想做类似的事情

In my test I want to do something like

A a = mock(A.class);
B expected = new B();
Mockito.verify(a).foo(argThat(JUnitMatchers.hasItem(new BMatcher(expected)));

但是,hasItem匹配器返回Iterable<B>,而foo方法需要List<B>.有没有什么好的方法可以验证该方法是否正确调用?

However, the hasItem matcher returns an Iterable<B> while the foo method expects a List<B>.Is there any good way of verifying the method is called properly?

推荐答案

您可以使用ArgumentCaptor.

 @Captor
 ArgumentCaptor<List<B>> captor;

 // then in test
 ...
 verify(a).foo(captor.capture());
 List<B> values = captor.getValue();
 assertThat(values, IsIterableContainingInOrder.containingInOrder(new BMatcher(expected));
 ...

我将@Captor用作快捷方式,并且它也可能是List<B>而不是List.这要求在@Before方法中使用MockitoAnnotations.init(this).

I used the @Captor as a shortcut and also to that it could be a List<B> instead of just List. This requires the use of MockitoAnnotations.init(this) in an @Before method.

这篇关于Hamcrest hasItem和Mockito验证不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:14
查看更多