2013-07-06 34 views
2

拋出的checked exception我有下面的界面問題想用的Mockito

public interface Interface1 { 
    Object Execute(String commandToExecute) throws Exception; 
} 

然後我試圖嘲弄,所以我可以測試類的行爲,將調用它:

Interface1 interfaceMocked = mock(Interface1.class); 
when(interfaceMocked.Execute(anyString())).thenThrow(new Exception()); 
Interface2 objectToTest = new ClassOfInterface2(interfaceMocked); 
retrievePrintersMetaData.Retrieve(); 

但編譯器告訴我,有一個未處理的異常。 的檢索方法的定義是:

public List<SomeClass> Retrieve() { 
    try { 
     interface1Object.Execute(""); 
    } 
    catch (Exception exception) { 
     return new ArrayList<SomeClass>(); 
    } 
} 

的文檔的Mockito只顯示RuntimeException的用途,而我還沒有看到在計算器上類似的事情。 我正在使用Java 1.7u25和mockito 1.9.5

回答

2

假設你的測試方法沒有聲明它拋出了Exception,編譯器是絕對正確的。這條線:

when(interfaceMocked.Execute(anyString())).thenThrow(new Exception()); 

...上Interface1一個實例調用Execute。這可能會導致Exception,所以您需要捕獲它或聲明您的方法拋出它。

我個人建議只聲明測試方法拋出Exception。沒有其他人會關心這個聲明,而你真的不想接受它。

+0

解決問題。我期待Mockito會照顧它。尚未習慣檢查異常的具體情況。 –

0

如果您的方法返回並引發錯誤,則不應該有問題。現在如果你的方法返回void,你將不能拋出錯誤。

現在真正的事情是,你不是測試你的接口拋出一個異常,而是你正在測試在這個方法中拋出異常時會發生什麼。

public List<SomeClass> Retrieve() { 
    try { 
     interface1Object.Execute(""); 
    } 
    catch (Exception exception) { 
     return handleException(exception); 
    } 
} 

protected List<SomeClass> handleException(Exception exception) { 
    return new ArrayList<SomeClass>(); 
} 

然後你只需調用你的handleException方法,並確保它返回正確的東西。如果你需要確保你的接口拋出一個異常,那麼對於你的接口類來說這是一個不同的測試。

你不得不爲單行做一個方法,但如果你想要可測試的代碼,有時候會發生這種情況。