Skip to content
mentoor

Topic 3 of 5 · 5 min read

Over-mocking and fake test doubles

Goal: Decide which mocks in a generated test hide the behaviour under test and replace them with a fake, a real dependency or a contract test.

A mock should replace something slow, external or non-deterministic, never the logic you are trying to test. AI assistants mock freely, because a mock makes a test easy to write and easy to pass. Too many mocks leave a test that checks the mocks.

Check yourself · 1 of 3

Which dependency is the best candidate for a mock in a unit test?

Choose one answer

Why it matters

Mocks have two costs. First, they can hide the behaviour under test. Second, they drift: the real payment API changes its response, the mock keeps the old shape, and the suite stays green while production fails. A mock only repeats what its author believed the dependency does.

The vocabulary

Martin Fowler's note separates the types. A stub returns canned answers. A mock also checks that it was called in a certain way. A fake is a working light version, such as an in-memory repository. A spy wraps the real thing and records calls.

How to review a generated test

  1. List every mock in the test. For each, ask: is this external, slow or random?
  2. If the mock replaces code in your own module, delete it and use the real one.
  3. Check what is verified. Asserting that a method "was called once with X" tests the wiring, not the result. Prefer asserting the outcome: the returned value, the saved row, the sent message.
  4. For anything that crosses a boundary, check how the mock stays honest: a fake used in other tests, a recorded real response, or a contract test run against the real service.

Before and after

// Weak: every collaborator mocked, only calls verified
test("registers user", async () => {
  const repo = { save: vi.fn() };
  const mailer = { send: vi.fn() };
  await register({ email: "a@x.com" }, repo, mailer);
  expect(repo.save).toHaveBeenCalled();
  expect(mailer.send).toHaveBeenCalled();
});

This passes even if register saves an empty object. Use an in-memory fake and check the data:

test("registers user and stores the email", async () => {
  const repo = new InMemoryUserRepo();
  const mailer = new FakeMailer();
  await register({ email: "a@x.com" }, repo, mailer);
  expect((await repo.findByEmail("a@x.com"))?.email).toBe("a@x.com");
  expect(mailer.sent[0].to).toBe("a@x.com");
});

What goes wrong

  • Mocking your own code. The test then proves nothing about it.
  • Stale mocks. The mock returns a field the real API removed.
  • Over-specified calls. Asserting exact call order makes every refactor break the test.
  • No integration test anywhere. Unit tests with mocks pass, and the parts do not work together.

Examples

Mock that has drifted

vi.mock("./payments", () => ({
  charge: async () => ({ status: "ok" }),
}));

The provider now returns { state: "succeeded" }. The mock still says status: "ok", the suite is green, and production fails at checkout. A contract test that calls the provider's sandbox would have failed first.

Replacing a mock with a fake

A generated test mocks db.query to return two fixed rows. Replace it with an in-memory SQLite database or a fake repository seeded with the same rows. The query code, ordering and filters now run for real, and a bug in the filter fails the test.

Key points

  • Mock only what is external, slow or random, and never the logic under test.
  • A mock repeats the author's belief about a dependency, so it can drift from the real API.
  • Prefer asserting outcomes such as returned values, saved data and sent messages over call counts.
  • An in-memory fake or a contract test keeps a test double honest against the real service.
  • Keep at least one integration test that uses the real parts together.

Common mistakes

  • Mocking a function from the same module that the test claims to cover.
  • Verifying only that a method was called, not what the code produced.
  • Letting a mock keep an old response shape after the real API changed.
  • Having no test that runs the real database or service at all.

Check yourself · 2 of 3

A generated test asserts only that mailer.send was called once. What is the most useful improvement?

Choose one answer

Check yourself · 3 of 3

A mock of a vendor API keeps returning the old response format after the vendor changes it. What guards against this?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic