問題描述
我試圖讓我的一個模擬對象在調用特定方法時拋出一個檢查異常.我正在嘗試以下方法.
I'm trying to have one of my mocked objects throw a checked Exception when a particular method is called. I'm trying the following.
@Test(expectedExceptions = SomeException.class)
public void throwCheckedException() {
List<String> list = mock(List.class);
when(list.get(0)).thenThrow(new SomeException());
String test = list.get(0);
}
public class SomeException extends Exception {
}
但是,這會產生以下錯誤.
However, that produces the following error.
org.testng.TestException:
Expected exception com.testing.MockitoCheckedExceptions$SomeException but got org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method!
Invalid: com.testing.MockitoCheckedExceptions$SomeException
查看 Mockito 文檔,他們只使用RuntimeException
,難道不能用Mockito從一個mock對象中拋出checked Exceptions嗎?
Looking at the Mockito documentation, they only use RuntimeException
, is it not possible to throw checked Exceptions from a mock object with Mockito?
推薦答案
檢查 列表.get(int index)
方法被聲明為僅拋出擴展 RuntimeException
的 IndexOutOfBoundException
.
您正試圖告訴 Mockito 拋出一個異常 SomeException()
,該異常 該特定方法調用無法拋出該異常.
Check the Java API for List.
The get(int index)
method is declared to throw only the IndexOutOfBoundException
which extends RuntimeException
.
You are trying to tell Mockito to throw an exception SomeException()
that is not valid to be thrown by that particular method call.
進一步澄清.
List 接口不提供從 get(int index)
方法拋出一個經過檢查的異常,這就是 Mockito 失敗的原因.
當您創建 mocked List 時,Mockito 將使用 List 的定義.class 來創建它的 mock.
To clarify further.
The List interface does not provide for a checked Exception to be thrown from the get(int index)
method and that is why Mockito is failing.
When you create the mocked List, Mockito will use the definition of List.class to creates its mock.
您使用 when(list.get(0)).thenThrow(new SomeException()) 指定的行為
與 List API 中的方法簽名不匹配,因為 get(int index)
方法不會拋出 SomeException()
所以 Mockito 失敗.
The behavior you are specifying with the when(list.get(0)).thenThrow(new SomeException())
doesn't match the method signature in List API, because get(int index)
method does not throw SomeException()
so Mockito fails.
如果你真的想這樣做,那么讓 Mockito 拋出一個 new RuntimeException()
甚至更好地拋出一個 new ArrayIndexOutOfBoundsException()
因為 API 指定這是要拋出的唯一有效異常.
If you really want to do this, then have Mockito throw a new RuntimeException()
or even better throw a new ArrayIndexOutOfBoundsException()
since the API specifies that that is the only valid Exception to be thrown.
這篇關于使用 Mockito 從模擬中拋出已檢查的異常的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!