2013-06-03 66 views
18

我想写一个单元测试,并做到这一点我正在写一个Mockito模拟的声明,但我似乎无法得到日食认识到我的返回值有效。不能返回Class对象与Mockito

下面是我在做什么:

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

.getParameterType()返回类型为Class<?>,所以我不明白为什么日食说,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的问题,还是我做错了什么?

回答

9

我不知道为什么你会得到这个错误。它必须与返回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; 
    } 


} 
+0

是的,它似乎必须是一个问题与日食或mockito。我能够实施你的建议,并解决了这个问题,所以谢谢! – CorayThan

+0

@CorayThan它不是Eclipse。这在Intellij中也不能编译。 –

+0

在NetBeans中一样。 –

44

此外,稍微更简洁的方式来解决这个问题是用做语法,而不是当的。

doReturn(User.class).when(methodParameter).getParameterType(); 
+1

好的提示!这应该被接受! –

+0

这是最干净的解决方案。 – Scott

+0

真棒......最干净的解决方案。非常感谢。 –

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

OngoingStubbing<Class<?>>通过Mockito.when返回是不一样的类型ongoingStubbing,因为每一个 '?'通配符可以绑定到不同的类型。

为了使各类比赛,你需要明确指定类型参数:

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

部分:'Mockito。当时是关键。感谢你的回答。 –

+0

在我看来,使用明确的打字是比目前投票的“正确”答案更优雅的解决方案 –

1

我找到了代码示例这里有点混乱,在使用methodParameter.getParameterType()在接受答案的第一次使用的SandBoxTest。在我做了更多的挖掘之后,我发现another thread pertaining to this issue提供了一个更好的例子。这个例子明确了我需要的Mockito调用是doReturn(myExpectedClass).when(myMock).callsMyMethod(withAnyParams)。使用这种形式可以让我嘲笑Class的返回。希望这篇文章能够帮助有人在未来寻找类似的问题。