Can#39;t return Class Object with Mockito(无法使用 Mockito 返回类对象)
问题描述
我正在尝试编写一个单元测试,为此我正在为 Mockito 模拟编写一个 when 语句,但我似乎无法让 eclipse 认识到我的返回值是有效的.
I'm trying to write a unit test, and to do that I'm writing a when statement for a Mockito mock, but I can't seem to get eclipse to recognize that my return value is valid.
这就是我正在做的事情:
Here's what I'm doing:
Class<?> userClass = User.class;
when(methodParameter.getParameterType()).thenReturn(userClass);
.getParameterType()
的返回类型是Class<?>
,所以不明白eclipse为什么说,方法thenReturn(Class<capture#1-of ?>) 类型为 OngoingStubbing<Class<capture#1-of ?>>不适用于参数 (Class<capture#2-of ?>)
.它提供了转换我的 userClass,但这只会使一些乱码 eclipse 说它需要再次转换(并且不能转换).
The return type of .getParameterType()
is Class<?>
, so I don't understand why eclipse says, The method thenReturn(Class<capture#1-of ?>) in the type OngoingStubbing<Class<capture#1-of ?>> is not applicable for the arguments (Class<capture#2-of ?>)
. It offers to cast my userClass, but that just makes some garbled stuff eclipse says it needs to cast again (and can't cast).
这只是 Eclipse 的问题,还是我做错了什么?
Is this just an issue with Eclipse, or am I doing something wrong?
推荐答案
另外,一个更简洁的解决方法是使用 do 语法而不是 when.
Also, a slightly more terse way to get around this is to use the do syntax instead of when.
doReturn(User.class).when(methodParameter).getParameterType();
这篇关于无法使用 Mockito 返回类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法使用 Mockito 返回类对象


基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01