本文介紹了調用未存根的方法時拋出 RuntimeException的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在使用 Mockito.我想在調用未存根的方法時拋出 RuntimeException
.
I'm using Mockito. I want to throw a RuntimeException
when an unstubbed method is called.
有什么辦法嗎?
推薦答案
您可以為模擬設置默認答案.所有未存根的方法都將使用此默認答案.
You can set a default answer for a mock. All methods that aren't stubbed will use this default answer.
public void testUnstubbedException() {
// Create a mock with all methods throwing a RuntimeException by default
SomeClass someClass = mock( SomeClass .class, new RuntimeExceptionAnswer() );
doReturn(1).when(someClass).getId(); // Must use doReturn
int id = someClass.getId(); // Will return 1
someClass.unstubbedMethod(); // Will throw RuntimeException
}
public static class RuntimeExceptionAnswer implements Answer<Object> {
public Object answer( InvocationOnMock invocation ) throws Throwable {
throw new RuntimeException ( invocation.getMethod().getName() + " is not stubbed" );
}
}
請注意,您不能將 when
與此功能一起使用,因為該方法在 when
之前調用(mockito when() 調用如何工作?),它會在之前拋出 RuntimeException
模擬進入存根模式.
Note that you cannot use when
with this functionality, since the method is called before when
(How does mockito when() invocation work?) and it will throw a RuntimeException
before the mock goes into stubbing mode.
因此,您必須使用 doReturn
才能使其工作.
Therefore, you must use doReturn
for this to work.
這篇關于調用未存根的方法時拋出 RuntimeException的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!