Problem: for one of my unit-tests, I want to simulate throwing an exception (io.netty.handler.timeout.TimeoutException
) in combination with Mockito. However, Java won't allow this because the exception is package-protected.
Right now I have the following bit of code:
doAnswer(invocation -> {
throw new TimeoutException("test-description");
}).when(someObject).someMethod();
This bit of code does not compile, but I would like to know if there are any alternatives for simulating throwing this exception.
CodePudding user response:
The class io.netty.handler.timeout.TimeoutException
itself is public, but its constructors are package-private. You can mock the exception:
doThrow(TimeoutException.class).when(someObject).someMethod();
or:
doThrow(mock(TimeoutException.class)).when(someObject).someMethod();