以下代码显示了我的问题.实际上,我正在尝试使用Mockito的ArgumentCaptor来验证方法是否使用某个具体类调用一次.如果可能的话,我想在这里使用ArgumentCaptor,但我开始怀疑我需要使用自定义的ArgumentMatcher.
问题是线Mockito.verify(模拟).receive(captor.capture()); (编辑:将此添加到下面的代码中)失败并出现TooManyActualInvocations异常(2而不是1).我想了解为什么会发生这种情况 – Mockito的执行效果不佳还是由于泛型的类型擦除造成的限制?
public class FooReceiver { public void receive(Foo foo) { } } public interface Foo { } public class A implements Foo { } public class B implements Foo { } public class TestedClass { private FooReceiver receiver; public TestedClass(FooReceiver receiver) { this.receiver = receiver; } public void doStuff() { receiver.receive(new A()); receiver.receive(new B()); } } public class MyTest { @Test public void testingStuff() { // Setup FooReceiver mocked = Mockito.mock(FooReceiver.class); TestedClass t = new TestedClass(mocked); // Method under test t.doStuff(); // Verify ArgumentCaptor<B> captor = ArgumentCaptor.forClass(B.class); Mockito.verify(mocked).receive(captor.capture()); // Fails here Assert.assertTrue("What happened?",captor.getValue() instanceof B); } }
编辑:
对于任何有兴趣的人,我最终做到了这一点:
// Verify final B[] b = new B[1]; ArgumentMatcher<B> filter = new ArgumentMatcher<B>() { @Override public boolean matches(Object argument) { if(argument instanceof B) { b[0] = (B) argument; return true; } return false; } } Mockito.verify(mocked).receive(Mockito.argThat(filter));
解决方法
您还可以使用Mockito.isA来验证参数是否属于特定类:
verify(mock).init(isA(ExpectedClass.class));