You can try something like the 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);
});