Hamcrest hasItem and Mockito verify inconsistency

自闭症网瘾萝莉.ら 提交于 2019-12-13 04:36:40

问题


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)));

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?


回答1:


You could use an 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));
 ...

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.




回答2:


You can use the 'argThat' method in the Mockito Matchers class to convert from a hamcrest Matcher to a mockito argument matcher:

import static org.mockito.Matchers.argThat;
import org.hamcrest.Matchers;
import org.hamcrest.Matcher;
//....
public static <T> List<T> listWithItem(Matcher<T> m)
{
    return (List<T>)argThat(Matchers.hasItem(m));
}


来源:https://stackoverflow.com/questions/17174192/hamcrest-hasitem-and-mockito-verify-inconsistency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!