繁体   English   中英

无法使用 Mockito 返回类对象

[英]Can't return Class Object with Mockito

我正在尝试编写一个单元测试,为此我正在为 Mockito 模拟编写一个 when 语句,但我似乎无法让 eclipse 识别我的返回值是有效的。

这是我在做什么:

Class<?> userClass = User.class;
when(methodParameter.getParameterType()).thenReturn(userClass);

.getParameterType()的返回类型是Class<?> ,所以我不明白为什么 eclipse 说, 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?>) 它提供投射我的 userClass,但这只会产生一些乱码,eclipse 说它需要再次投射(并且不能投射)。

这只是 Eclipse 的问题,还是我做错了什么?

此外,解决此问题的一种更简洁的方法是使用do语法而不是when。

doReturn(User.class).when(methodParameter).getParameterType();
Class<?> userClass = User.class;
OngoingStubbing<Class<?>> ongoingStubbing = Mockito.when(methodParameter.getParameterType());
ongoingStubbing.thenReturn(userClass);

所述OngoingStubbing<Class<?>>通过返回Mockito.when是不相同的类型ongoingStubbing因为每个“?” 通配符可以绑定到其他类型。

为了使类型匹配,您需要显式指定type参数:

Class<?> userClass = User.class;
Mockito.<Class<?>>when(methodParameter.getParameterType()).thenReturn(userClass);

我不确定为什么会收到此错误。 它必须与返回Class<?>有特殊关系。 如果返回Class则代码可以正常编译。 这是您所做的模拟,并且此测试通过。 我认为这也将为您工作:

package com.sandbox;

import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import static org.mockito.Mockito.*;

import static junit.framework.Assert.assertEquals;

public class SandboxTest {

    @Test
    public void testQuestionInput() {
        SandboxTest methodParameter = mock(SandboxTest.class);
        final Class<?> userClass = String.class;
        when(methodParameter.getParameterType()).thenAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                return userClass;
            }
        });

        assertEquals(String.class, methodParameter.getParameterType());
    }

    public Class<?> getParameterType() {
        return null;
    }


}

我发现这里的代码示例与首先在接受的答案的SandBoxTest中使用的methodParameter.getParameterType()有点混淆。 经过更多的挖掘之后,我发现了另一个与此问题相关的主题 ,它提供了一个更好的示例。 这个例子清楚地表明,我需要的Mockito调用是doReturn(myExpectedClass).when(myMock).callsMyMethod(withAnyParams)。 使用该表格可以让我模拟Class的返回。 希望本文能对将来寻找类似问题的人有所帮助。

您可以简单地从课程中删除))

Class userClass = User.class;
when(methodParameter.getParameterType()).thenReturn(userClass);

还有两个解决方案:

在这里,我们将编译错误换成未经检查的分配警告:

Class<?> userClass = User.class;
when(methodParameter.getParameterType()).thenReturn((Class)userClass);

没有警告的更简洁的解决方案是

Class<?> userClass = User.class;
when(methodParameter.getParameterType()).thenAnswer(__ -> userClass);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM