Java 带有Mockito.when()和泛型类型推断的奇怪泛型边缘大小写

Java 带有Mockito.when()和泛型类型推断的奇怪泛型边缘大小写,java,generics,mockito,Java,Generics,Mockito,我正在编写一个使用Mockito的java.beans.PropertyDescriptor的测试用例,我想模拟getPropertyType()的行为,以返回任意的Class对象(在我的例子中,String.Class)。通常,我会通过调用: // we already did an "import static org.mockito.Mockito.*" when(mockDescriptor.getPropertyType()).thenReturn(String.class); 然而

我正在编写一个使用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>)
找不到返回的符号方法(java.lang.Class)
但当我指定类型参数而不是依赖推断时:

Mockito.<Class<?>>when(mockDescriptor.getPropertyType()).thenReturn(String.class);
Mockito.
PropertyDescriptor#getPropertyType()
返回
类的对象,其中
表示“这是一个类型,但我不知道它是什么”。让我们称这种类型为“X”。因此
when(mockDescriptor.getPropertyType())
创建一个
ongoingstubing
,其方法
thenReturn(Class)
只能接受
类的对象。但是编译器不知道这个“X”是什么类型,因此它会抱怨您传入了任何类型的
类。我认为这也是编译器抱怨在
集合上调用
add(…)
的原因

当您在
When
方法上为类型显式指定
Class
时,您并不是说
mockDescriptor.getPropertyType()
返回一个
Class
,而是说
When
返回一个
ongoingstubing
// the inferred type is Class<"some type">
Mockito.when(mockDescriptor.getPropertyType())

// the specified type is Class<"any type">
Mockito.<Class<?>>when(mockDescriptor.getPropertyType())
The method thenReturn(Class<capture#1-of ?>) in the type OngoingStubbing<Class<capture#1-of ?>> is not applicable for the arguments (Class<String>)