Mockito:使用有界通配符返回类型的存根方法

编程入门 行业动态 更新时间:2024-10-20 05:37:53
本文介绍了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

我相信编译器在 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:使用有界通配符返回类型的存根方法

本文发布于:2023-10-31 04:43:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545040.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:存根   通配符   类型   方法   Mockito

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!