2015-12-16 20 views
10

考慮以下方法:如何在不運行方法的情況下模擬方法調用和返回值?

public boolean isACertainValue() { 
     if(context.getValueA() != null && context.getValueA().toBoolean() == true) { 
     if(context.getType() != null && context.getType() == ContextType.certainType) { 
      return true; 
     } 
    } 
    return false; 
} 

我沒有寫這個代碼,它是醜陋的地獄,它完全是過於複雜,但我有它的工作。

現在我想測試一個方法,該方法依賴於對此方法的調用。

我以爲我可以應付這樣的:

Mockito.when(spy.isACertainValue()).thenReturn(true);,因爲這是我想測試的情況。

但它不工作,因爲它仍然是調用方法體:/

我得到nullpointers或者說我相處

misusing.WrongTypeOfReturnValue線的東西;布爾值不能由getValueA()返回。 getValueA()應返回值a

於是,我(作爲一種解決方法)做:

Mockito.when(contextMock.getValueA()).thenReturn(new ValueA());Mockito.when(contextMock.getType()).thenReturn(ContextType.certainType);

但後來我得到一個空指針,我不能似乎能夠進行調試。

那麼,在這種情況下它是如何完成的?

+1

這正是如何做到這一點,但也許有在值a您需要進一步的在您的測試值,所以你也應該嘲笑返回的對象,而不僅僅是迴歸一個使用(默認)構造函數實例化的實例。 – Stultuske

回答

13

當你調用

Mockito.when(spy.isCertainValue()).thenReturn(true); 

方法isCertainValue()是越來越這裏調用。這就是Java的工作方式:要評估Mockito.when的參數,必須對spy.isCertainValue()的結果進行評估,以便方法必須被調用。

如果你不希望這樣的事情發生,你可以使用the following construct

Mockito.doReturn(true).when(spy).isCertainValue(); 

這將有同樣的效果嘲諷,但該方法不會與這個被調用。

+0

謝謝,我現在正在跟蹤...我得到一個nullpointer tho xD我很討厭這個程序,這是一個可憎的:X – Sorona

+0

斷開的鏈接。你在哪裏設置間諜? – powder366

+0

它爲我工作。它停止投擲NPE。謝謝Tunaki! – Dish

0

此代碼是正確的:

Mockito.when(contextMock.getType()).thenReturn(ContextType.certainType); 

但你得到的NullPointerException,因爲你沒有定義嘲諷值應該是定義,以及我使用的春天,在我的上下文文件時,我定義@Autowired豆我定義它是這樣的:

<bean id="contextMock" class="org.mockito.Mockito" factory-method="mock"> 
    <constructor-arg value="com.example.myspringproject.bean.ContextMock" /> 
</bean> 
相關問題