gpt4 book ai didi

java - 为什么 Mockito 类型匹配器匹配不相关的对象?

转载 作者:行者123 更新时间:2023-11-30 10:17:09 25 4
gpt4 key购买 nike

我需要一个依赖于参数类型的模拟行为。我试过使用 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.

关于java - 为什么 Mockito 类型匹配器匹配不相关的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49767789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com