Skip to content

How it works

The spy sits between the test and the collaborator, records (method, args, timestamp) on every call, and returns the real response — so the test can check the ledger without losing the object's behaviour.

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.