我需要一个模拟的行为来依赖于参数类型。
我尝试使用Matchers.any(Class<>)
来提供两种行为:
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() {}));
}
}
测试失败:
org.junit.ComparisonFailure: expected:<[A] received> but was:<[B] received>
我做错了什么?
Mockito版本1.9.5
答案 0 :(得分:1)
这是预期的行为。根据{{3}}
的文件任何类型的对象,不是给定类的必需对象。提供类参数只是为了避免强制转换。