使用 mockito 存根具有依赖泛型参数的方法

编程入门 行业动态 更新时间:2024-10-20 07:37:28
本文介绍了使用 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 存根具有依赖泛型参数的方法

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

发布评论

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

>www.elefans.com

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