Course contentsShow
← Software Engineering
Lesson 468 of 1,93314. Test DoublesFree lesson

Spies: Recording Interactions for Verification

Using spies to capture how dependencies are called while still executing real behavior for later inspection.

Spies: Recording Interactions for Verification

You'll learn how spies let you observe and verify how your code interacts with dependencies while keeping real behavior intact.

What Is a Spy?

A spy is a test double that wraps around a real object (or function), allowing it to execute normally while secretly recording every interaction. Think of it like a security camera in a store: customers shop normally, but you can review the footage later to see what happened.

Unlike stubs that replace behavior with canned responses, spies let the real code run—they just take notes about who called what, with which arguments, and how many times.

When to Use Spies

Spies are perfect when you need to verify interactions but don't want to replace the actual implementation. For example, you might want to confirm that your code:

  • Called a logging function with the right message
  • Invoked a callback exactly once
  • Passed specific arguments to a dependency
  • Called methods in a particular order

The real logging still happens, the callback still executes—you're just checking that your code is using these dependencies correctly.

Spies vs. Other Test Doubles

While stubs return fake data and fakes provide simplified working implementations, spies are about observation and verification. You can inspect a spy after your test runs to answer questions like "Was this called?" or "What arguments were passed?"

Spies bridge the gap between testing with real dependencies and complete isolation.

Key Takeaway: Spies record how dependencies are called while executing real behavior, letting you verify interactions without losing actual functionality—perfect when you care more about how something was used than what it returns.