0

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

4

1 回答 1

0

我评论了另一个问题,最后有一个答案(不是被接受的)可能适合您的情况。


一种解决方法是使用一种willAnswer()方法。

例如,以下工作(并且不抛出 MockitoException 但实际上在这里根据需要抛出一个检查异常)使用BDDMockito

given(someObj.someMethod(stringArg1)).willAnswer(invocation -> { 
    throw new Exception("abc msg");
});

普通 Mockito 的等价物将使用 doAnswer 方法


这是该答案的直接链接:https ://stackoverflow.com/a/48261005/13210306

于 2021-04-23T15:32:18.420 回答