java – 具有Mockito.when()和泛型类型推断的奇怪的泛型边缘情况

我正在编写一个使用Mockito的 java.beans.PropertyDescriptor的测试用例,我想嘲笑getPropertyType()的行为来返回任意的Class<?>对象(在我的例子中是String.class).通常,我会通过调用
// we already did an "import static org.mockito.Mockito.*"
when(mockDescriptor.getPropertyType()).thenReturn(String.class);

但是,奇怪的是,这不编译:

cannot find symbol method thenReturn(java.lang.class<java.lang.String>)

但是当我指定类型参数而不是依赖于推断:

Mockito.<Class<?>>when(mockDescriptor.getPropertyType()).thenReturn(String.class);

一切都是笨蛋.为什么在这种情况下编译器不能正确推断when()的返回类型?我从来没有像这样指定参数.

解决方法

PropertyDescriptor#getPropertyType()返回Class<?>的对象,其中?意思是“这是一种类型,但我不知道是什么”.我们称这种类型为“X”.所以当(mockDescriptor.getPropertyType())创建一个OngoingStubbing< Class< X>时,其方法thenReturn(Class< X>)只能接受Class< X>的对象.但是编译器不知道这个“X”是什么类型的,所以它会抱怨你传递任何类型的类.我认为这是编译器抱怨在集合<?&gt ;.上调用add(...)的原因. 当您明确指定Class<?>对于when方法的类型,你不是说mockDescriptor.getPropertyType()返回一个Class<?>,你说的是返回一个OngoingStubbing< Class>>>.然后,编译器会检查以确保您遇到的类型与Class<?>因为getPropertyType()返回“Class< X>”我之前提到,它当然符合Class<?>你指定

所以基本上

// the inferred type is Class<"some type">
Mockito.when(mockDescriptor.getPropertyType())

// the specified type is Class<"any type">
Mockito.<Class<?>>when(mockDescriptor.getPropertyType())

在我的IDE中,原始代码错误消息是

The method thenReturn(Class<capture#1-of ?>) in the type OngoingStubbing<Class<capture#1-of ?>> is not applicable for the arguments (Class<String>)

捕获#1的?是上面描述的“X”.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...