5. Mock vs. Spy in Mockito

Now – let’s discuss the difference between Mock and Spy in Mockito – not the theoretical differences between the two concepts, just how they differ within Mockito itself.

When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it.

On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.

org.mockito.exceptions.misusing.NotAMockException:
Argument passed to when() is not a mock!
Example of correct stubbing:
doThrow(new RuntimeException()).when(mock).someMethod();

Thankfully it is quite clear from the Mockito error message what the problem is here. In our example, the list object is not a mock. The Mockito when() method expects a mock or spy object as the argument.

As we can also see the Exception message even describes what a correct invocation should look like. Now that we have a better understanding of what the problem is, let’s fix it following the recommendation:

Hey Alex,
First off – thanks for the feedback.
I was looking for where the MockitoJUnit4Runner is used by I can’t seem to find it.
Also – the initMocks calls isn’t necessary if you’re using the runner, but if you’re not – then the call is required.
Hope that helps. Cheers,
Eugen.