2016-12-26 38 views
1

現在我有一個方法來測試使用Mockito。但是這種方法很複雜。在同樣的方法中,我需要新的兩個對象都是相同的類型。如何用相同的方法模擬第二個對象?

Timestamp beginTimestamp = new Timestamp(Long.parseLong(beginTimeLong)); 
Timestamp endTimestamp = new Timestamp(System.currentTimeMillis()); 

我想嘲笑第二個目的,endTimestamp,拋出一個Exception,但我不能避免beginTimestamp的影響。現在的問題是如何嘲笑第二個目的,endTimeStamp,只有,並使其拋出了一個異常時,我打電話endTimestamp's一定的方法,如:

endTimestamp.getTime() 

我試着寫其中顯示我的測試代碼

@Ignore 
public void getSynPotentialShopBeginTimeAndEndTest4() throws Exception { 
    Timestamp beginTimestamp = PowerMockito.mock(Timestamp.class); 
    Timestamp endTimestamp = PowerMockito.mock(Timestamp.class); 
    PowerMockito.whenNew(Timestamp.class).withAnyArguments().thenReturn(beginTimestamp).thenReturn(endTimestamp); 

    when(endTimestamp.getTime()).thenThrow(RuntimeException.class); 
    redisService.getSynPotentialShopBeginTimeAndEnd(); 
} 

它也不起作用。這些代碼沒有任何紅色波形下劃線,但是當我試圖運行它,我得到這樣一個例外:

org.mockito.exceptions.base.MockitoException: 
    Incorrect use of API detected here: 


You probably stored a reference to `OngoingStubbing` returned by `when()` and called stubbing methods like `thenReturn()` on this reference more than once. 
Examples of correct usage: 
    when(mock.isOk()).thenReturn(true).thenReturn(false).thenThrow(exception); 
    when(mock.isOk()).thenReturn(true, false).thenThrow(exception); 

有另一種解決方案,我可以解決這個問題?無論如何,只有當問題得到解決,沒關係。

回答

2

試試這個

PowerMockito.whenNew(Timestamp.class).withAnyArguments().thenReturn(beginTimestamp,endTimestamp); 

而不是PowerMockito.whenNew(Timestamp.class).withAnyArguments().thenReturn(beginTimestamp).thenReturn(endTimestamp);

+0

謝謝你這麼這麼這麼多,它的工作原理! –

相關問題