Java – use mockito’s argumentcaptor class to match subclasses
•
Java
The following code shows my problem In fact, I'm trying to use mockito's argumentcaptor to verify whether a method is called once with a specific class If possible, I want to use argumentcaptor here, but I'm beginning to doubt that I need to use a custom argumentmatcher
The problem is the line mockito Verify receive(captor.capture()); (edit: add this to the following code) fails with toomanyactualinvocations exception (2 instead of 1) I want to know why this happens – is mockito performing poorly or is it limited by the type erasure of generics?
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);
}
}
Editor: for anyone interested, I finally did this:
// 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));
Solution
You can also use mockito Isa to verify whether the parameter belongs to a specific class:
verify(mock).init(isA(ExpectedClass.class));
Mockito JavaDoc
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
