加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:46:03 所属栏目:Java 来源:网络整理
导读:我正在编写一个使用Mockito的 java.beans.PropertyDescriptor的测试用例,我想嘲笑getPropertyType()的行为来返回任意的Class?对象(在我的例子中是String.class).通常,我会通过调用: // we already did an "import static org.mockito.Mockito.*"when(mockD
我正在编写一个使用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”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读