2

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?

Gaurav Jha
  • 161
  • 1
  • 7

3 Answers3

3

You can use Mockito.reset() to clear any mocking setup you have done on a particular mock (for example Mockito.reset(someMock)).

NOTE: It is usually better to make your tests smaller so you don't need to use reset. If you are using @MockBean, the mocks are reset after each test method by default. This default behaviour can be changed via the reset parameter on the annotation.

BugsOverflow
  • 386
  • 3
  • 19
Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
2

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.

Georgii Lvov
  • 1,771
  • 1
  • 3
  • 17
0

You can create a nested class using @Nested and move all your exception methods into it and create a separate setup for those functions only. This structure will help you segregate all the similar methods

D_J
  • 55
  • 2
  • 10