I need a behaviour of a mock to depend on argument type.
I've tried to use Matchers.any(Class<>)
to provide two behaviours:
public class MockitoTest {
public interface ToMock {
String accept(Object object);
}
interface A {
}
interface B {
}
@Test
public void doAnswer() {
ToMock mock = Mockito.mock(ToMock.class);
Mockito.doReturn("A received").when(mock).accept(Matchers.any(A.class));
Mockito.doReturn("B received").when(mock).accept(Matchers.any(B.class));
Assert.assertEquals("A received", mock.accept(new A() {}));
Assert.assertEquals("B received", mock.accept(new B() {}));
}
}
Test fails with:
org.junit.ComparisonFailure: expected:<[A] received> but was:<[B] received>
What am I doing wrong?
Mockito version 1.9.5
This is expected behaviour. According to the documentation of Matchers.any(Class)
Any kind object, not necessary of the given class. The class argument is provided only to avoid casting.