gpt4 book ai didi

java - Mockito 与方法参数 any() 类型不匹配

转载 作者:行者123 更新时间:2023-11-30 06:26:20 29 4
gpt4 key购买 nike

我正在使用 Mockito 1.10.19 来测试方法调用。我有一些类调用 execute 方法

public class Argument {
public D execute(B b){
return new D();
}
}
class A extends B {
}
class B {
}
class C extends B {
}
class D {}

测试

public class ArgumentTest {
@Test
public void execute() throws Exception {
Argument argument = mock(Argument.class);
A a = mock(A.class);
D d = mock(D.class);
when(argument.execute(any(A.class))).thenAnswer(
(invocation) -> {
Object[] args = invocation.getArguments();
Object mock = invocation.getMock();
return d;
}
);

argument.execute(new C());
}

}

当我运行此测试时,即使参数 any(A.class),它也会匹配 when 匹配器。

这是怎么回事?

最佳答案

any(...) 中没有类型检查 - source :

This method doesn't do any type checks, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.

快速浏览一下源代码,我们可以发现任何类型的参数都匹配成功,并且类参数仅用于生成默认返回值。

public static <T> T any(Class<T> clazz) {
return (T) reportMatcher(Any.ANY).returnFor(clazz);
}
<小时/>

它还可能使具有相同数量参数的方法重载难以测试。不过,通过执行显式 instanceof 检查的 argThat 匹配器可以避免这种情况。

关于java - Mockito 与方法参数 any() 类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47128211/

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