java – 使用Mockito的ArgumentCaptor类来匹配子类

前端之家收集整理的这篇文章主要介绍了java – 使用Mockito的ArgumentCaptor类来匹配子类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下代码显示了我的问题.实际上,我正在尝试使用Mockito的ArgumentCaptor来验证方法是否使用某个具体类调用一次.如果可能的话,我想在这里使用ArgumentCaptor,但我开始怀疑我需要使用自定义的ArgumentMatcher.

问题是线Mockito.verify(模拟).receive(captor.capture()); (编辑:将此添加到下面的代码中)失败并出现TooManyActualInvocations异常(2而不是1).我想了解为什么会发生这种情况 – Mockito的执行效果不佳还是由于泛型的类型擦除造成的限制?

  1. public class FooReceiver {
  2. public void receive(Foo foo) {
  3.  
  4. }
  5. }
  6.  
  7. public interface Foo {
  8. }
  9.  
  10. public class A implements Foo {
  11. }
  12.  
  13. public class B implements Foo {
  14. }
  15.  
  16. public class TestedClass {
  17. private FooReceiver receiver;
  18. public TestedClass(FooReceiver receiver) {
  19. this.receiver = receiver;
  20. }
  21.  
  22. public void doStuff() {
  23. receiver.receive(new A());
  24. receiver.receive(new B());
  25. }
  26. }
  27.  
  28. public class MyTest {
  29.  
  30. @Test
  31. public void testingStuff() {
  32. // Setup
  33. FooReceiver mocked = Mockito.mock(FooReceiver.class);
  34. TestedClass t = new TestedClass(mocked);
  35.  
  36. // Method under test
  37. t.doStuff();
  38.  
  39. // Verify
  40. ArgumentCaptor<B> captor = ArgumentCaptor.forClass(B.class);
  41. Mockito.verify(mocked).receive(captor.capture()); // Fails here
  42.  
  43. Assert.assertTrue("What happened?",captor.getValue() instanceof B);
  44. }
  45. }

编辑:
对于任何有兴趣的人,我最终做到了这一点:

  1. // Verify
  2. final B[] b = new B[1];
  3. ArgumentMatcher<B> filter = new ArgumentMatcher<B>() {
  4. @Override
  5. public boolean matches(Object argument) {
  6. if(argument instanceof B) {
  7. b[0] = (B) argument;
  8. return true;
  9. }
  10. return false;
  11. }
  12. }
  13. Mockito.verify(mocked).receive(Mockito.argThat(filter));

解决方法

您还可以使用Mockito.isA来验证参数是否属于特定类:
  1. verify(mock).init(isA(ExpectedClass.class));

Mockito JavaDoc

猜你在找的Java相关文章