为什么 Mockito 类型匹配器匹配不相关的对象?
Why Mockito type matchers match unrelated objects?
我需要一个依赖于参数类型的模拟行为。
我尝试使用 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
这是预期的行为。根据 Matchers.any(Class)
的文档
Any kind object, not necessary of the given class. The class argument is provided only to avoid casting.
我需要一个依赖于参数类型的模拟行为。
我尝试使用 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
这是预期的行为。根据 Matchers.any(Class)
Any kind object, not necessary of the given class. The class argument is provided only to avoid casting.