使用Mockito模拟具有通用参数的类

编程入门 行业动态 更新时间:2024-10-25 16:20:45
本文介绍了使用Mockito模拟具有通用参数的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有一种用泛型参数嘲笑类的干净方法?假设我必须模拟一个类 Foo< T> ,我需要将它传递给期望 Foo< Bar> 。我可以很容易地做到以下几点:

Is there a clean method of mocking a class with generic parameters? Say I have to mock a class Foo<T> which I need to pass into a method that expects a Foo<Bar>. I can do the following easily enough:

Foo mockFoo = mock(Foo.class); when(mockFoo.getValue).thenReturn(new Bar());

假设 getValue()返回泛型类型 T 。但是当我稍后将它传递给期望 Foo< Bar> 的方法时,会有小猫。是铸造这样做的唯一手段?

Assuming getValue() returns the generic type T. But that's going to have kittens when I later pass it into a method expecting Foo<Bar>. Is casting the only means of doing this?

推荐答案

我认为你需要投它,但它不应该太bad:

I think you do need to cast it, but it shouldn't be too bad:

Foo<Bar> mockFoo = (Foo<Bar>) mock(Foo.class); when(mockFoo.getValue).thenReturn(new Bar());

更多推荐

使用Mockito模拟具有通用参数的类

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

发布评论

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

>www.elefans.com

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