2014-04-04 73 views
0

我有以下的單元測試:時的Mockito - 然後返回錯誤

@Test 
public void testGenerateFileName(){ 

GregorianCalendar mockCalendar = Mockito.mock(GregorianCalendar.class); 
Date date = new Date(1000); 
Mockito.when(mockCalendar.getTime()).thenReturn(date); 
... 
} 

在第三行我收到以下錯誤:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: Date cannot be returned by getTimeInMillis() getTimeInMillis() should return long 
*** If you're unsure why you're getting above error read on. Due to the nature of the syntax above problem might occur because: 
1. This exception *might* occur in wrongly written multi-threaded tests. Please refer to Mockito FAQ on limitations of concurrency testing. 
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
    - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method. 

這究竟是爲什麼?我沒有使用getTimeInMillis()

回答

3

問題是方法GregorianCalendar.getTime()是最終的,所以Mockito不能攔截方法調用。

另一種方法是使用Apache Commons Lang中的日期轉換爲Calendar,所以當你調用getTime它返回你所期望

DateUtils.toCalendar(date) 

如果你想要去野外,您可以使用PowerMock的值模擬最終字段,但我認爲當你有一個更簡單的選擇時,增加PowerMock的複雜性是不值得的。

另一點。你應該儘量避免嘲笑你不擁有的對象,這對於單元測試和模擬對象來說非常重要。這裏有一個reference,有一些關於這種做法的鏈接。

最後,因爲它可能適用於您的項目:從您可以獲取當前時間的時間引入「Clock」對象是一個很好的做法,測試可以操縱此時鐘以返回「靜態」當前時間。

編輯

的Java 8包括Clock抽象,它具有可以通過調用Clock.fixed()Clock.tick()Clock.tickSeconds()Clock.tickMinutes()獲得用於測試的具體實現理想......或者你可以寫自己的實現時鐘。

相關問題