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?

You can achieve this behavior with a thenAnswer call:

when(myRepository.findById(any())).thenAnswer(invocationOnMock -> {
    throw new MyException(invocationOnMock.getArgument(0, String.class));
});

Leave a Comment