39

我正在尝试编写一个单元测试,为此我正在为 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 ?>). 它提供了转换我的用户类,但这只会使一些乱码 eclipse 说它需要再次转换(并且不能转换)。

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

4

5 回答 5

86

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

doReturn(User.class).when(methodParameter).getParameterType();
于 2013-08-14T21:43:38.707 回答
29
Class<?> userClass = User.class;
OngoingStubbing<Class<?>> ongoingStubbing = Mockito.when(methodParameter.getParameterType());
ongoingStubbing.thenReturn(userClass);

OngoingStubbing<Class<?>>返回的类型Mockito.whenongoingStubbing每个 '?' 不同 通配符可以绑定到不同的类型。

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

Class<?> userClass = User.class;
Mockito.<Class<?>>when(methodParameter.getParameterType()).thenReturn(userClass);
于 2013-08-15T00:59:24.340 回答
13

我不确定您为什么会收到此错误。归来一定有什么特殊的关系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;
    }


}
于 2013-06-03T04:56:17.027 回答
3

您可以简单地从类中删除))

Class userClass = User.class;
when(methodParameter.getParameterType()).thenReturn(userClass);
于 2018-09-25T15:26:16.323 回答
1

我发现这里的代码示例与在已接受答案的 SandBoxTest 中首次使用的 methodParameter.getParameterType() 的使用有些混淆。在我做了更多的挖掘之后,我发现了另一个与这个问题有关的线程,它提供了一个更好的例子。这个例子清楚地表明了我需要的 Mockito 调用是 doReturn(myExpectedClass).when(myMock).callsMyMethod(withAnyParams)。使用该表单可以让我模拟 Class 的返回。希望这篇笔记能帮助将来搜索类似问题的人。

于 2015-08-13T12:51:56.260 回答