Mockito Spy

Last Updated on

Spy Objects

A Mockito spy allows us to create a spy object from a real object with similar behavior where each method can be stubbed out when needed. It is ideal for testing legacy code as you cannot invoke a few testing impediment methods from your code under test, and also, you cannot mock a class that needs to be tested. A spy can stub these impediments without mocking the code under test, stub nontestable methods so that other methods can be tested easily, and verify interactions between two real objects without the need of stubbing any of their methods. It is also known as ‘partial mocking’.

Spy object vs mock object

A mock object created via

is devoid of behavior defined for the class-to-mock. The following codes demonstrate this main difference.

Real and Spy objects are NOT one and the same

Spy objects are created from real objects. Any changes to the spy object do not affect the real object it based itself on. Same goes for the real object. Any changes to it do not affect the spy object created based on it. Here are the codes to prove it.

Download the codes



Karl San Gabriel

Professional Software Developer