所以现在我正在从 Mockito 1.* 迁移到 2.*,我不明白为什么在 doAnswer 中使用 getArgument() 时会出现转换问题。我的意思是,当我尝试在其他方法参数中调用 getArgument() 或尝试在检索到的对象上链接方法时。 这是与mockito 1.*一起使用的代码
doAnswer(invocation -> {
try (InputStream inputStream = invocation.getArgumentAt(0, SomeResource.class).getResource().getInputStream()) {
IOUtils.copy(inputStream, invocation.getArgumentAt(1, OutputStream.class));
}
return null;
}).when(mockedService).downloadFile(any(), any());
迁移到 2.* 后将 getArgumentAt() 更改为 getArgument() 失败,因为找不到类型的“getResource()”方法。由于类型不兼容,从调用中获取第二个参数也不起作用。
doAnswer(invocation -> {
try (InputStream inputStream = invocation.getArgument(0).getResource().getInputStream()) {
IOUtils.copy(inputStream, invocation.getArgument(1));
}
return null;
}).when(mockedService).downloadFile(any(), any());
我必须在第二个参数中更改为显式转换,或者显式保存到新引用,第一个参数也是如此。 该代码有效:
doAnswer(invocation -> {
final SomeResource input = invocation.getArgument(0);
final OutputStream outputStream = invocation.getArgument(1);
try (InputStream inputStream = input.getResource().getInputStream()) {
IOUtils.copy(inputStream, outputStream);
}
return null;
}).when(mockedService).downloadFile(any(), any());
不知道为什么。
最佳答案
方法getArgument
是一个通用方法。它具有以下签名:
<T> T getArgument(int index)
请参阅javadoc .
这在 Java 8 之前是不可能的,Java 8 添加了 Generalized Target-Type Inference通常返回类型类被用作参数之一(就像在使用 Mockito 1.* 的示例中一样)。
因此,当您将结果分配给具体类型的变量时,不需要进行强制转换,因为它可以被推断出来。当您将 is 传递给 IOUtils.copy() 时,它无法推断出单个具体类型,因为 copy 方法已重载。如果将其传递给未重载的方法,则无需显式强制转换即可工作。
关于generics - 为什么在mockito 2中使用 "doAnswer"时getArgument()不会隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54365641/