Skip to content

Stubs, Spies, Mocks, Oh My!

Posted on:November 1, 2024

Earlier today there was a short conversation in one of my Discord channels about how stubs are used in testing frameworks. You’ll often hear about stubs, mocks, and spies—each serving a unique role in your tests. Here’s a quick breakdown:

Stubs

Stubs are simple. They provide fixed, predetermined responses to method calls, ensuring your code has a controlled, predictable environment to run in. They don’t care about how they’re used, just that they respond correctly. Great for isolating a unit under test!

Mocks

Mocks are more demanding. They let you set expectations on how your code interacts with them, and they’ll fail the test if those expectations aren’t met. If you want to verify that methods are called with specific arguments or in a specific order, mocks have your back. Think behavior verification!

Spies

Spies are like the secret agents of test doubles. They observe and record how your methods are used, without requiring strict expectations upfront. Want to let a method run but still verify interactions afterward? Spies let you do just that. They’re perfect for keeping an eye on things while staying flexible in your test code.

TL;DR

Use the right one based on whether you’re testing state, behavior, or just want to keep an eye on things. Happy testing!