Mockito test a void method throws an exception
JavaExceptionMockingMockitoJava Problem Overview
I have a method with a void
return type. 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)
Any ideas how I can get the method to throw a specified exception?
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
Java Solutions
Solution 1 - Java
The parentheses are poorly placed.
You need to use:
doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
^
and NOT use:
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
^
This is explained in the documentation
Solution 2 - Java
If you ever wondered how to do it using the new BDD style of Mockito:
willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));
And for future reference one may need to throw exception and then do nothing:
willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));
Solution 3 - Java
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);
});