无法使用Mockito返回Class对象

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

这就是我正在做的事情:

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

返回类型.getParameterType()Class ,所以我不明白为什么eclipse说, The method thenReturn(Class) in the type OngoingStubbing<Class> is not applicable for the arguments (Class) 。 它提供了投射我的userClass,但这只是使一些乱码的东西eclipse说它需要再次施放(并且不能施放)。

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

另外,稍微简洁一点的方法是使用do语法而不是when。

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

OngoingStubbing>返回的OngoingStubbing>ongoingStubbing因为每个’?’ 通配符可以绑定到不同的类型。

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

 Class userClass = User.class; Mockito.>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() { @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))

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