Photo by Tobias Tullius on Unsplash

I Spy with My Little Mockito…

Why Spy on Your Dependencies?

Kenneth Kousen
6 min readMar 8, 2023

--

https://pragprog.com/newsletter/

The Mockito testing framework generates mocks, stubs, and spies for your dependencies. Most people are familiar with mocks and stubs. In this article we’ll talk about spies — the interceptors that let you test how your classes interact with their real dependencies.

📝 Note: This example is really simple. The Mockito wiki page called “Using Spies (and Fakes)” contains three much more sophisticated examples. If you want me to go through more complex examples, leave me a note in the comments. For the time being, let me show you a trivial example, because:

1. You may still find it useful, and
2. Hey, not everything has to be complicated, right?

A spy is a class that sits in between the class you’re testing and its actual dependent objects. It’s the very definition of one of the primary laws of computer science: Every problem in computer science is solved by adding a layer of indirection — something between me and where I want to go. A spy sits in front of an actual, instantiated dependency.

Spying on a List

--

--

Kenneth Kousen
The Pragmatic Programmers

Author of the books Mockito Made Clear, Help Your Boss Help You, Kotlin Cookbook, Modern Java Recipes, Gradle Recipes for Android, and Making Java Groovy