問題描述
我正在使用 Mockito.我想在調(diào)用未存根的方法時拋出 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
之前調(diào)用(mockito when() 調(diào)用如何工作?),它會在之前拋出 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.
這篇關于調(diào)用未存根的方法時拋出 RuntimeException的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!