使用 Mockito 模拟具有泛型参数的类 [英] Using Mockito to mock classes with generic parameters

查看:39
本文介绍了使用 Mockito 模拟具有泛型参数的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种干净的方法来模拟带有泛型参数的类?假设我必须模拟一个 Foo 类,我需要将它传递给一个需要 Foo 的方法.我可以很容易地做到以下几点:

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 的方法时,它将会有小猫.铸造是这样做的唯一方法吗?

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?

推荐答案

我认为你确实需要投射它,但应该不会太糟糕:

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 模拟具有泛型参数的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆