← Back to Backend, page 3

backend-0042 · Medium mid

What are the different kinds of test doubles (dummy, stub, spy, mock, fake), and how do you choose between state-based and interaction-based tests?

Test doubles replace real collaborators in tests. A dummy fills an argument and is never used. A stub returns canned answers. A spy records how it was called so you can check it afterwards. A mock is a spy with expectations that fail the test if they are not met. A fake is a working but simplified implementation (an in-memory repository). Prefer state-based assertions with fakes where possible, because they survive refactoring. Use interaction checks (spies, mocks) for side effects that leave your system, such as sending an email.

Full answer

Kinds

  • Dummy: passed around but never used (a logger the code does not call in this case).
  • Stub: provides indirect input, a fixed answer (a clock that always returns the same time, a rate service that returns 1.5).
  • Spy: a stub that also remembers its calls (arguments, count). You assert on the record.
  • Mock: pre-programmed with expectations about calls, and verifies them. In practice many libraries blur spy and mock.
  • Fake: a lightweight real implementation (in-memory database, local file storage). It has behaviour of its own.

Choosing

  • State-based verification: run the code, then check the result or the state of the fake. It is less tied to how the code works, so refactoring does not break the test.
  • Interaction-based verification: check that a call happened (the email was sent once, with the right address). Use it when the call itself is the result and there is no state to look at.
  • Over-mocking makes tests pass while the real wiring is broken. Do not mock what you do not own (wrap third-party clients in your own interface and test the adapter with an integration test). Do not mock simple value objects.
  • Use real infrastructure in integration tests so that doubles are not the only evidence.
javascript
const assert = require('node:assert');
const { mock } = require('node:test');

// The code under test: registers a user, then sends a welcome email.
async function register({ repo, mailer, clock, logger }, email) {
  if (await repo.findByEmail(email)) return { ok: false, reason: 'duplicate' };
  const user = await repo.save({ email, createdAt: clock() });
  await mailer.send(email, 'Welcome!');
  return { ok: true, user };
}

// Fake: a simple but working in-memory repository.
const fakeRepo = () => { const rows = []; return { rows, findByEmail: async (e) => rows.find((r) => r.email === e), save: async (u) => { rows.push({ id: rows.length + 1, ...u }); return rows.at(-1); } }; };
const stubClock = () => '2026-12-04T00:00:00Z';                       // Stub: a fixed answer
const dummyLogger = null;                                             // Dummy: never used here
const spyMailer = () => ({ send: mock.fn(async () => {}) });          // Spy / mock: records calls

(async () => {
  const deps = { repo: fakeRepo(), mailer: spyMailer(), clock: stubClock, logger: dummyLogger };

  const first = await register(deps, 'asha@example.com');
  assert.strictEqual(first.ok, true);
  assert.deepStrictEqual(deps.repo.rows.map((r) => r.createdAt), ['2026-12-04T00:00:00Z']);        // state-based check (fake + stub)
  console.log('state check : user stored with the stubbed time -> pass');

  assert.strictEqual(deps.mailer.send.mock.callCount(), 1);                                          // interaction check (spy)
  assert.deepStrictEqual(deps.mailer.send.mock.calls[0].arguments, ['asha@example.com', 'Welcome!']);
  console.log('spy check   : one email, correct arguments -> pass');

  const second = await register(deps, 'asha@example.com');
  assert.deepStrictEqual(second, { ok: false, reason: 'duplicate' });
  assert.strictEqual(deps.mailer.send.mock.callCount(), 1);
  console.log('duplicate   : rejected and no second email -> pass');

  // A refactoring that does not change behaviour (save first, then check) still passes the state checks,
  // but a test that asserted "findByEmail was called once" would break. Interaction checks are more fragile.
  const failing = { ...deps, mailer: { send: mock.fn(async () => { throw new Error('smtp down'); }) }, repo: fakeRepo() };
  await assert.rejects(() => register(failing, 'ravi@example.com'), /smtp down/);
  console.log('failure path: a failing mailer surfaces the error ->', failing.repo.rows.length, 'row was already saved (is that what you want?)');
})();

Uses node:assert and the mock helper of node:test, with no test runner needed. The last line shows a design question that the double made visible. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): state check : user stored with the stubbed time -> pass spy check : one email, correct arguments -> pass duplicate : rejected and no second email -> pass failure path: a failing mailer surfaces the error -> 1 row was already saved (is that what you want?)

Key points

  • Stubs give input, spies and mocks check output calls, fakes work in memory.
  • Prefer state-based assertions with fakes.
  • Use interaction checks for side effects that leave the system.
  • Do not over-mock, and do not mock types you do not own.
  • Back doubles with integration tests.

Common mistakes

  • Mocking the database client so no SQL is ever tested.
  • Asserting call order and counts that are not part of the behaviour.
  • Sharing mutable fakes between tests.
  • Mocking value objects and pure functions.
  • Mocking a third-party library directly instead of wrapping it.

Follow-ups

  • What is the difference between a mock and a spy in your favourite library?
  • How do you keep a fake in line with the real implementation?
  • When is a test with real PostgreSQL better than a fake?

Tips

  • Give one sentence per double.
  • State the case for state-based checks.
  • Mention what not to mock.