Member-only story
Improve Your Testing #14: Mocks, Spies, and Stubs
Which is which and when to use them to write better, more maintainable tests.
Although many of us know what a mock is, everything starts to get fuzzy when we begin to hear about things like stubs or spies. What are they? Are they also mocks? Or are they different? And if so, when do we use one or another, and how do we know if we should use them?
Test double
Gerard Meszaros introduced the term “test double” in his 2007 book “xUnit Test Patterns.” He did this with the goal of separating each type of mock, thus facilitating and simplifying their use and the decision of when to use them.
When he introduced the word, he tried to find an unused term and drew inspiration from movies. Specifically from stunt doubles, specialized actors in scenes where the protagonist is not available who replace them hoping it won’t affect the movie’s outcome.
This is exactly what a test double is: an artifact that we can use in our code as a replacement for another and that can work with the rest of the code while simultaneously providing a clear response about whether the code works or not.
Thus, we can talk about 5 different types of test doubles:
- Dummy: values that are…