本文翻译自:Mockito test a void method throws an exception
I have a method with a void
return type. 我有一个void
返回类型的方法。 It can also throw a number of exceptions so I'd like to test those exceptions being thrown. 它还可以引发许多异常,因此我想测试所引发的异常。 All attempts have failed with the same reason: 所有尝试均以相同的原因失败:
The method when(T) in the type Stubber is not applicable for the arguments (void) Stubber类型中的when(T)方法不适用于参数(void)
Any ideas how I can get the method to throw a specified exception? 有什么想法可以获取引发指定异常的方法吗?
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
#1楼
参考:https://stackoom.com/question/11azR/Mockito测试void方法会引发异常
#2楼
The parentheses are badly placed. 括号放置不正确。 You must use 您必须使用
doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
^
and not 并不是
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
^
This is explained in the documentation 在文档中对此进行了解释
#3楼
If you ever wondered how to do it using the new BDD style of Mockito: 如果您想知道如何使用新的BDD样式的Mockito来做到这一点:
willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));
And for future reference one may need to throw exception and then do nothing: 为了将来参考,可能需要抛出异常,然后什么也不做:
willThrow(new Exception()).willNothing().given(mockedObject).methodReturningVoid(...));