I am unable to create an instance of SQLServerException because the ctors are all internal. Getting below error when using SQLException
org.mockito.exceptions.base.MockitoException: Checked exception is invalid for this method!
Method signature (on SQLServerPreparedStatement):
public boolean execute() throws SQLServerException, SQLTimeoutException
and... public final class SQLServerException extends SQLException
Mock:
val fakeCmd : SQLServerPreparedStatement = mock()
...
whenever(fakeCmd.execute()).thenThrow(SQLException()) // this line fails
What am I doing wrong? Shouldn't I be able to throw the base/super exception?
Re Suggested Question:
The suggested question is very different from what I'm asking, the op in the other question is trying to throw SomeException
which is not thrown by List.get
nor in the inheritance tree
If you see "Method signature (on SQLServerPreparedStatement)" above, the method throws SQLServerException
=> public final class SQLServerException extends SQLException
But it doesn't like whenever(fakeCmd.execute()).thenThrow(SQLException())
Further, the accepted answer as pointed out is to throw RuntimeException
because IndexOutOfBoundsException extends RuntimeException
In this case, so is SQLServerException extends SQLException
I commented about another question and there is a answer (not the accepted one) in the end that may be suitable in your case.
A workaround is to use a willAnswer()
method.
For example the following works (and doesn't throw a MockitoException but actually throws a checked Exception as required here) using BDDMockito
:
given(someObj.someMethod(stringArg1)).willAnswer(invocation -> {
throw new Exception("abc msg");
});
The equivalent for plain Mockito would to use the doAnswer method
Here is the direct link to that answer: https://stackoverflow.com/a/48261005/13210306