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 the spy by ourselves together with some additional configuration (refer to the Creating mocks with a custom configuration recipe in Chapter 2, Creating Mocks, for a description of all possible configurations).
For this recipe, we will reuse...