我有一个void
返回类型的方法。它也可以抛出一些异常,所以我想测试那些抛出的异常。所有尝试都失败了,原因相同:
类型 Stubber 中的方法 when(T) 不适用于参数 (void)
有什么想法可以让方法抛出指定的异常吗?
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
括号位置不好。
你需要使用:
doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
^
并且不使用:
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
^
这在文档中进行了解释
如果你想知道如何使用新的 BDD 风格的 Mockito 来做到这一点:
willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));
为了将来参考,可能需要抛出异常然后什么也不做:
willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));
You can try something like below:-
given(class.method()).willAnswer(invocation -> {
throw new ExceptionClassName();
});
In my case, I wanted to throw an explicit exception for a try block,my method block was something like below
public boolean methodName(param) throws SomeException{
try(FileOutputStream out = new FileOutputStream(param.getOutputFile())) {
//some implementation
} catch (IOException ioException) {
throw new SomeException(ioException.getMessage());
} catch (SomeException someException) {
throw new SomeException (someException.getMessage());
} catch (SomeOtherException someOtherException) {
throw new SomeException (someOtherException.getMessage());
}
return true;
}
I have covered all the above exceptions for sonar coverage like below
given(new FileOutputStream(fileInfo.getOutputFile())).willAnswer(invocation -> {
throw new IOException();
});
Assertions.assertThrows(SomeException.class, () ->
{
ClassName.methodName(param);
});