2013-06-03 62 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的返回。希望這篇文章能夠幫助有人在未來尋找類似的問題。