Creating spies with custom configuration

There might be some cases in which you would like to provide some additional configuration to your spy (for example, making the spy serializable or turning on Mockito logging). Even though Mockito doesn't provide a straightforward solution to do it, it is possible to pass such a configuration to the spy. As a reminder, you should have very legitimate reasons to use a spy in your code. Otherwise, it most likely signifies that there is something wrong with the design of your code.

Getting ready

As presented in the previous recipe, the Mockito.spy method has only a single parameter: the spied instance. But as we can see, internally, it's a mock that by default calls real methods. So what we can do is create ...

Get Mockito Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.