Mockito: Stubbing Methods That Return Type With Bounded Wild-Cards(Mockito:使用有界通配符返回类型的存根方法)
问题描述
考虑这段代码:
public class DummyClass {
public List<? extends Number> dummyMethod() {
return new ArrayList<Integer>();
}
}
public class DummyClassTest {
public void testMockitoWithGenerics() {
DummyClass dummyClass = Mockito.mock(DummyClass.class);
List<? extends Number> someList = new ArrayList<Integer>();
Mockito.when(dummyClass.dummyMethod()).thenReturn(someList); //Compiler complains about this
}
}
编译器抱怨试图为 dummyMethod() 存根的行.关于如何处理返回具有有界通配符类型的存根方法的任何指针?
The compiler complains about the line that's trying to stub the behavior for dummyMethod(). Any pointers on how one goes about stubbing methods that return a type with bounded wild-cards?
推荐答案
你也可以使用非类型安全的方法 doReturn 为此,
You can also use the non-type safe method doReturn for this purpose,
@Test
public void testMockitoWithGenerics()
{
DummyClass dummyClass = Mockito.mock(DummyClass.class);
List<? extends Number> someList = new ArrayList<Integer>();
Mockito.doReturn(someList).when(dummyClass).dummyMethod();
Assert.assertEquals(someList, dummyClass.dummyMethod());
}
作为 讨论 在 Mockito 的 google 组上.
as discussed on Mockito's google group.
虽然这比 thenAnswer 简单,但再次注意它不是类型安全的.如果您担心类型安全,millhouse 的answer 是正确的.
While this is simpler than thenAnswer, again note that it is not type safe. If you're concerned about type safety, millhouse's answer is correct.
要清楚,这是观察到的编译器错误,
To be clear, here's the observed compiler error,
OngoingStubbing) 方法扩展号码>>不适用于参数 (List
我相信编译器在 when 调用期间分配了第一个通配符类型,然后无法确认 thenReturn 调用中的第二个通配符类型相同.
I believe the compiler has assigned the first wildcard type during the when call and then cannot confirm that the second wildcard type in the thenReturn call is the same.
thenAnswer 似乎没有遇到此问题,因为它接受通配符类型,而 thenReturn 采用必须捕获的非通配符类型.来自 Mockito 的 OngoingStubbing,
It looks like thenAnswer doesn't run into this issue because it accepts a wildcard type while thenReturn takes a non-wildcard type, which must be captured. From Mockito's OngoingStubbing,
OngoingStubbing<T> thenAnswer(Answer<?> answer);
OngoingStubbing<T> thenReturn(T value);
这篇关于Mockito:使用有界通配符返回类型的存根方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Mockito:使用有界通配符返回类型的存根方法
基础教程推荐
- 将 Windows 证书导入 Java 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
