A Spy is a test double in Gerard Meszaros' taxonomy from xUnit Test Patterns (2007): a Stub that also records how it was called, which methods, with what arguments and how many times. It returns canned responses and silently logs every interaction for later inspection. Assertions follow in the test body after the action, unlike a Mock, whose pre-programmed expectations fail immediately when violated.
Test Double: Spy (Meszaros)
Details
Core Concepts:
- Purpose
-
A Stub that also records how it was called — which methods, with what arguments, how many times. Assertions happen after the action, not as expectations before.
- Behavior
-
Returns canned responses (like a Stub) and silently records all interactions for later inspection.
- Distinction from Mock
-
A Spy records and lets you assert afterward. A Mock has pre-programmed expectations that fail immediately if violated.
- Key Proponent
-
Gerard Meszaros ("xUnit Test Patterns", 2007)
When to Use:
-
Tell an LLM: "Create a Spy test double that records calls for later assertion"
-
When you need to verify interactions but want assertions in the test body, not in setup
-
Auditing what happened during a test without constraining the order of operations
-
When the exact interaction pattern matters but you want flexible assertion
Related Anchors:
-
Test Double (Meszaros) — umbrella taxonomy
-
Stub — Spy without call recording
-
Mock — pre-programmed expectations instead of post-hoc assertion