Software Development

Mockito Spy

Spy Objects

[wp_ad_camp_5]

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

[wp_ad_camp_4]

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

https://github.com/Turreta/mockito-spy-samples

[wp_ad_camp_3]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like