Skip to content

Spy

A spy is a test double that records the calls it receives so the test can assert on them after the fact; unlike a mock, a spy does not fail by itself, it just produces a ledger.

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.

  1. 2007 — Meszaros formalises Test Spy in xUnit Test Patterns

  2. 2007 — Fowler's Mocks Aren't Stubs positions spies in the taxonomy

  3. 2011 — Sinon.js ships spies, stubs and mocks as distinct primitives

  4. 2014 — Jest introduces jest.fn() with spy semantics

  5. 2020 — Mockito and pytest consolidate spy patterns in Java/Python

  6. 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
2007 · Meszaros formaliza Test Spy
2011 · Sinon.js con spies, stubs y mocks como primitivas
2014 · Jest jest.fn() con semántica de spy
5 · dobles de pruebadummy, stub, spy, mock, fake
1 · assertion mínima por spy para no ser dead weight

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

Etymology

Origin: borrowed

  • spy (noun): from Old French espier, "to watch"; espionage sense from the 16th century

Semantic network

SpyTest doublsoftware-tStubMockFakeDummyTest doubl

● broader ● narrower ● related

Broader

Related

Used in the garden

Sources