Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Simulate throwing an exception that is package protected

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading