本文介绍了使用 mockito 存根具有依赖泛型参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图用像这样的依赖泛型参数存根一个方法:
Im trying to stub a method with dependend generic arguments like so:
<T extends Foo> void exampleMethod(Type<T> arg1, T arg2);使用 Mockito.但是当我尝试这样做时
using Mockito. But when I try to do this like this
verify(mock).exampleMethod(isA(Type.class), any());它不起作用,但给了我一个无限泛型错误.(我知道这不是存根,但这个例子更容易,归结为我认为的同样的事情.)
it does not work but gives me an unbounded generics error. (I know this is not stubbing but the example is easier this way and it boils down to the same thing I think.)
如果有人可以提供帮助,将不胜感激.
If anybody could help it would be much appreciated.
推荐答案这里的错误是 any() 返回一个类型 Object,该类型对 T 类型无效.泛型只负责警告.使用 any(Foo.class) 代替:
The error here is that any() returns a type Object, which isn't valid for type T. The generics are only responsible for a warning. Use any(Foo.class) instead:
public class MockTest { public static void main(String[] args) { MockTest sandbox = Mockito.mock(MockTest.class); // gives a type safety warning suppressable with @SuppressWarnings verify(sandbox).exampleMethod(isA(Class.class), any(Foo.class)); // gives an unchecked cast warning suppressable with @SuppressWarnings verify(sandbox).exampleMethod((Class<Foo>) isA(Class.class), any(Foo.class)); // gives no warnings because the cast in the helper method below verify(sandbox).exampleMethod(isAClassOf(Foo.class), any(Foo.class)); } @SuppressWarnings("unchecked") private static <T> Class<T> isAClassOf(Class<T> clazz) { return isA(Class.class); } <T extends Foo> void exampleMethod(Class<T> arg1, T arg2) { } }更多推荐
使用 mockito 存根具有依赖泛型参数的方法
发布评论