Definition
What it is
The distinction from a mock is subtle and it matters: a mock is pre-programmed with expectations ("this method must be called exactly once with these args"), and it fails the test if the contract is not honoured. A spy has no contract; it just logs what happened. The test inspects the log at the end and decides what to assert.
spy = Spy(real_repository)
service.create_user("ana@example.com")
assert spy.calls == [("save", ("ana@example.com",))]
Martin Fowler's 2007 taxonomy classifies spies as a kind of test double, alongside stubs, mocks, dummies and fakes [1]. Gerard Meszaros' xUnit Test Patterns describes them as "Test Spy" — a double that "captures indirect output" and makes it available for verification by the test itself [2].
Why it matters
A mock that says "exactly two calls, in this order, with these arguments" breaks when you refactor the implementation to make three calls with the same outcome. A spy that records "it called save twice with these args and send-email once" lets you assert only on what matters, and it survives refactors that preserve behaviour. Mozilla's engineering guidelines for Firefox's codebase, one of the largest test suites in open source, recommend spies for exactly this reason: strict mocks are expensive to maintain, spies are not [3].
The cost is that a spy does not catch missing calls by itself. If the production code stops calling save, the spy records zero calls; the test asserts and fails, but only because the test bothered to assert. A mock would have failed automatically. The trade is flexibility for a small assertion burden.
How it works
graph LR T[Test] --> S[Spy wrapper] S -->|records call| L[Call ledger] S -->|delegates| R[Real or fake object] R -->|returns| S S -->|returns| T L -.->|inspected after| A[Assertions] style S fill:#E8F5E9 style L fill:#E8F5E9
The three implementations in mainstream languages. Jest (JavaScript): jest.fn() produces a spy by default; mockImplementation attaches behaviour. Sinon (JavaScript): sinon.spy(obj, 'method') wraps an existing method; sinon.stub() returns a programmable stub. Mockito (Java): spy(realObject) wraps; verify(spy).method() asserts post-hoc. Python: unittest.mock.MagicMock(wraps=real) produces spy semantics. RSpec (Ruby): allow(obj).to receive(:msg).and_call_original is the spy pattern.
Mock vs spy vs stub
Aspect | Stub | Spy | Mock |
|---|---|---|---|
Returns | Fixed answer | Delegates to real | Expects specific answer |
Records calls | No | Yes | Yes |
Fails on its own | No | No | Yes (unmet expectation) |
Test asserts on | State | Ledger | Contract |
Refactor resilience | High | High | Low |
Common failures
Origin
Espionage uses "spy" for an operative who watches and reports. The software sense borrowed the metaphor in the mid-2000s as mocking frameworks matured and developers needed a double that observed rather than asserted. Meszaros' xUnit Test Patterns (2007) formalised it as one of five doubles; Fowler's Mocks Aren't Stubs (2007) placed it in the taxonomy; Sinon.js (2011) made it a first-class primitive in JavaScript testing, and Jest (2014) followed.
2007 — Meszaros formalises Test Spy in xUnit Test Patterns
2007 — Fowler's Mocks Aren't Stubs positions spies in the taxonomy
2011 — Sinon.js ships spies, stubs and mocks as distinct primitives
2014 — Jest introduces jest.fn() with spy semantics
2020 — Mockito and pytest consolidate spy patterns in Java/Python
2024 — Mozilla testing guidelines recommend spies over strict mocks
A Test Spy is a double that captures the indirect output of the system under test so that the test can verify the indirect output.
— Gerard Meszaros, *xUnit Test Patterns*, 2007
Evidence
FAQ
- Spy or mock?
Use a spy when you want the real behaviour and post-hoc verification; use a mock when the collaboration itself is the contract. If the test asserts "it called save once", a mock is more direct; if it asserts "the user was saved and an email was sent", a spy is more resilient.
- Should I spy on the real object or a fake?
Either works. Spying on the real object exercises the actual code path; spying on a fake isolates the unit. Choose based on what the test needs to prove.
- How do I assert on a spy?
Inspect the ledger.
expect(spy).toHaveBeenCalledWith(...)in Jest;sinon.assert.calledOnceWithExactly(spy, args)in Sinon;verify(spy).method(args)in Mockito. Pick one assertion per intent.- Can a spy replace a mock entirely?
No. A spy has no expectation contract, so it never fails on its own. If you want automatic failure on missing calls, use a mock.
Connections
Fowler, M. (2007). Mocks Aren't Stubs. https://martinfowler.com/articles/mocksArentStubs.html
Meszaros, G. (2007). xUnit Test Patterns. https://martinfowler.com/books/meszaros.html
Sinon.js (2024). Spies. https://sinonjs.org/releases/latest/spies/
Etymology
Origin: borrowed
spy(noun): from Old French espier, "to watch"; espionage sense from the 16th century
Semantic network
● broader ● narrower ● related
Used in the garden
- Unlock Success! 10 FREE Web Apps Your Competitors DON'T Want You To Know About (Smart Entrepreneur Edition) (2×)
- Unlock Your Day! 10 Secret Websites That Will Transform Your Productivity and Wallet (1×)
- 10 FREE Web Apps That Will Skyrocket Your Digital Marketing (Without Spending a Dime!) (1×)
- Bored of the Usual? 10 SECRET Websites That Will Transform Your Day (And Your Wallet!) (1×)
- Warning! 10 Secret Websites Your Browser Hides (And You'll Wish You Knew Sooner) (1×)
- 10 Secret Websites That Will Transform Your Day (and Your Wallet) (1×)
- Unlock Growth: 10 Free Web Apps Every Ambitious Entrepreneur MUST Know to Scale Rapidly (1×)
- 10 FREE Web Apps EVERY Content Creator and Entrepreneur MUST KNOW (The PROS' Secret!) (1×)
- Unlock Your Potential! 10 Secret Web Apps That Will Transform Your Day (Entrepreneurs & Content Creators Edition) (1×)
- Unlock Digital Success! 10 Secret Web Gems for Budget-Conscious Entrepreneurs (1×)
- 10 FREE Web Apps That Will Skyrocket Your Online Business (Zero-Budget Entrepreneurs Edition!) (1×)
- Stop Wasting Money! 10 FREE Web Apps Every Smart Entrepreneur Needs to Scale TODAY (1×)
- 10 Secret Web Apps That Will Skyrocket Your Success Without a Penny (Zero-Budget Entrepreneur Edition) (1×)
- 10 Secret Web Apps That Will Unleash Your Entrepreneurial Potential (Free or Nearly So!) (1×)
- The Secret Arsenal for Creators! 10 FREE Web Apps That Will Skyrocket Your Digital Success (Creators & Entrepreneurs Edition) (1×)
- Unlock Success! 10 Secret Web Gems for Digital Entrepreneurs That Will Transform Your Business (1×)
Sources
Fowler, M. (2007). Mocks Aren't Stubs. https://martinfowler.com/articles/mocksArentStubs.html
Meszaros, G. (2007). xUnit Test Patterns. https://martinfowler.com/books/meszaros.html
Sinon.js (2024). Spies. https://sinonjs.org/releases/latest/spies/