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

Mockito – doThrow (or thenThrow) with Exception constructed with passed argument

I’d like to check an input, and then throw an exception based on that input.\
Maybe something simple like this:

when(myRepository.findById(any()))
  .thenThrow(new MyException(getArguments()[0]);

Is something like this not possible? If not, is there an alternative?

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 :

You can achieve this behavior with a thenAnswer call:

when(myRepository.findById(any())).thenAnswer(invocationOnMock -> {
    throw new MyException(invocationOnMock.getArgument(0, String.class));
});
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