使用Mockito模拟具有通用参数的类 [英] Using Mockito to mock classes with generic parameters
本文介绍了使用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模拟具有通用参数的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文