Skip to content
mentoor

Topic 1 of 5 · 4 min read

Unit tests that pin real behaviour

Goal: Tell a unit test that checks behaviour from one that only mirrors the implementation, and rewrite the weak one so it fails when the code is wrong.

A good unit test fails when the behaviour is wrong; a bad one only repeats what the code already does. When an agent writes tests after writing the code, the second kind is very common.

Check yourself · 1 of 3

A test computes its expected value with the same formula the function uses. What is the main problem?

Choose one answer

Why it matters

A unit test is a small contract: given this input, the result is this. If the test copies the logic of the function, it can never disagree with it. You get a green suite, a coverage number and no protection. Agents such as Claude Code, Codex, Copilot and Cursor produce these tests easily, because the fastest way to make a test pass is to derive the expected value from the code under test.

How to write or review one

  1. Start from the rule, not the code. Write the expected value by hand from the requirement, for example "a 10 % discount on 200 is 180".
  2. Assert on outputs and visible effects, not on which private functions were called.
  3. Mock only what you do not own or cannot run fast: the clock, the network, a payment provider. Do not mock the function you are testing, or its pure helpers.
  4. Cover the edges the rule implies: zero, empty, the boundary value, the invalid input.
  5. Break the code on purpose. Flip a > to >=, return a constant, delete a line. If the suite stays green, the test is weak. Mutation tools such as Stryker automate this.

Before and after

// Weak: the expected value is computed with the same formula as the code
test("applies discount", () => {
  const price = 200, rate = 0.1;
  expect(applyDiscount(price, rate)).toBe(price - price * rate);
});

If applyDiscount has a bug in the formula, the test copies it and passes. The fixed version pins known values:

test("applies a 10 % discount", () => {
  expect(applyDiscount(200, 0.1)).toBe(180);
});
test("a rate of 0 leaves the price unchanged", () => {
  expect(applyDiscount(200, 0)).toBe(200);
});
test("rejects a rate above 1", () => {
  expect(() => applyDiscount(200, 1.5)).toThrow();
});

What goes wrong

  • Tautological tests. The expected value is built from the implementation, so the test cannot fail.
  • Over-mocking. Every collaborator is mocked and the test only checks that mocks were called in order. Refactor the code and the test breaks while the behaviour is fine; break the behaviour and it can still pass.
  • No failing assertion. The test calls the code but asserts nothing, or asserts something always true such as expect(result).toBeDefined().
  • Test edited to match the bug. When a test fails, the agent changes the expected value instead of the code. Always read test changes in a diff first.

Examples

The test that mirrors the code

def test_total():
    items = [Item(10), Item(5)]
    assert total(items) == sum(i.price for i in items)

The expected value uses the same idea as total. If total forgets tax or drops the last item in the same way, the test still passes. Replace it with assert total([Item(10), Item(5)]) == 15.

Everything mocked

const repo = { save: vi.fn() };
await createUser(repo, { email: "a@b.co" });
expect(repo.save).toHaveBeenCalled();

This passes even if createUser saves an empty object. Assert on what was saved: expect(repo.save).toHaveBeenCalledWith(expect.objectContaining({ email: "a@b.co" })), or use an in-memory repository and read the user back.

Key points

  • Write the expected value by hand from the requirement, never by reusing the code's own formula.
  • Assert on outputs and visible effects, not on which internal functions were called.
  • Mock the clock, the network and third-party services, but not the code under test.
  • Break the code on purpose: a test that still passes after a deliberate bug is not protecting anything.
  • When a test fails, decide whether the code or the test is wrong before letting an agent change either.

Common mistakes

  • Letting the agent generate expected values by running the code and pasting the output.
  • Counting a test as useful because it raises coverage while asserting almost nothing.
  • Mocking the function under test, or its pure helpers, so the test checks the mock.
  • Fixing a red test by editing the expected value without asking which side is wrong.

Check yourself · 2 of 3

Which expected value makes a stronger test for applyDiscount(200, 0.1)?

Choose one answer

Check yourself · 3 of 3

An agent's new test for a parser passes, but you suspect it is weak. Which quick check best tests that suspicion?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic