Search code examples
unit-testingexceptionjunitmockitospring-boot-test

How to unmock an exception using Mockito?


I am trying to mock a function for various results. First, I mocked it for throwing an exception as follows:

Mockito.when(ClassName.methodName(Matchers.any(), Matchers.any())).thenThrow(new ExceptionName());

Now, I want to mock for a case when it return some output. So, I am trying as follows:

    Mockito.when(ClassName.methodName(Matchers.any(), Matchers.any())).thenReturn(output);

But it is throwing exception(Maybe because I have already mocked it to throw exception)

How should I unmock it, so that I can use it to give proper output?


Solution

  • You can define behavior of mock for multiple calls as follows:

    when(ClassName.methodName(any(),any()))
                    .thenThrow(RuntimeException.class)
                    .thenReturn(output)
                    .thenCallRealMethod();
    

    When your mock is called in service for the first time it will be thrown RuntimeException, for the second will be returned output, for the third will be called a real method.