微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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”.

原文地址:https://www.jb51.cc/java/121467.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐