DEV Community

Darkø Tasevski
Darkø Tasevski

Posted on Originally published at darkotasevski.dev

TDD and mutation testing when coding agents write the tests

Test-driven development and mutation testing are both old ideas, and for a long time they were the kind of thing everyone agreed with and few teams did, because writing the test first was slow and running mutants was slower. With coding agents writing most of the code, and most of the tests too, and with us reading less and less of that code ourselves, I think both of them stopped being nice-to-haves, and this post is about why, with examples from a small test-first workflow for agents I put together recently (a pricing library that turns strings like "4.35" into integer cents, and a storefront in its own repository that uses it).

We don't read the code anymore

Most of the time we either don't read the code an agent writes, or we skim the diff for obvious mistakes (a wrong file, a deleted check, something that looks off), and the volume an agent produces in a day makes reading it line by line unrealistic anyway, since that would take away the whole point of having the agent. For years the tests were a second line of defence behind a person who wrote and read the code, and now they're often the only thing that has looked at the behaviour closely, which makes the quality of the tests matter a lot more than it used to.

When an agent says it's done, the evidence it usually points at is a passing test suite, and it says so with the same confidence whether those tests could ever fail or not. A test the agent writes after the code tends to describe what the code does, bugs included, so it goes green on the first run and keeps going green, and a test with a weak or missing assertion looks exactly like a good one in the output. And since the tests were also written by the agent and we skim them the same way we skim the code, nobody has checked the thing we're leaning on, unless the process checks it for us.

So the question for any test an agent hands us is "has anyone seen this fail when the code was wrong?", and both TDD and mutation testing are ways of answering yes.

Tests first, because the agent pays for it

The old argument against TDD was its cost, since a person had to write the test, watch it fail and only then write the code, and that's a lot of typing for something that feels obvious. With an agent the typing is free, so what's left is the useful part, which is that the tests come from the spec before any code exists for them to mirror, and the red step shows that each one can fail.

In that workflow every feature task in the plan was written test-first, and it paid off on the very first one. The tests for parsing "4.35" were written before the parser, the first implementation used floats

Math.trunc(Number(major) * 10 ** exponent)
Enter fullscreen mode Exit fullscreen mode

and converts without float error failed with

expected 434 to be 435
Enter fullscreen mode Exit fullscreen mode

because 4.35 * 100 is 434.99999999999994 in Js. The agent rewrote the parser to join digit strings instead of multiplying, which is the kind of bug a test written after the code would most likely have locked in, since 434 is what the code returned.

The red step only counts on the assertion

The catch is that a red step can be red for the wrong reason. The plan for that first task said this:

- [x] Step 2: Run them and watch them fail: `npx vitest run src/money.test.ts`.
      Expected: `fromMajor is not a function`.
Enter fullscreen mode Exit fullscreen mode

and fromMajor is not a function is thrown when the test calls the function, before Vitest gets anywhere near the expect, so every test that calls it directly fails the same way, including a test with no assertion at all. Tests that check for a thrown error are worse, since expect(() => fromMajor('1e3', 'USD')).toThrow(SyntaxError) fails with an assertion-looking expected error to be instance of SyntaxError, and a bare .toThrow() passes, because the TypeError is an error too.

A red step counts only when the test fails on its own assertion, for the reason the test is about.

The cheap fix is to stub every new export before the first run, so the functions exist and return something wrong:

export function fromMajor(major: string, currency: Currency): Money {
  return money(0, currency);
}
Enter fullscreen mode Exit fullscreen mode

Now pads short fractions fails with expected +0 to be 1050, a test with a forgotten expect passes (which is exactly what we want to see), and the SyntaxError test fails because nothing throws. A test that stays green under the stub, because its expected value happens to be zero, isn't proven either way and needs a second stub value or a mutant later.

Mutation testing for everything else

Plenty of tests never get a real red step, like tests changed after the code exists, tests added during review, and tests whose red step was the is not a function kind, and mutation testing covers those. A mutant is a one-line change to the code, like >= to > or dropping a $ from a regex, and it's killed when some test goes red because of it. If no test notices, either a test is missing or the ones we have don't assert what we think they do.

When I counted for that feature, the agent's log had kills for 9 of the 21 tests it added or changed, while the review at the end said every one of them had a recorded kill (I believed that until I counted). So we went through the other 12 by hand, one mutant per test, which means copying the file aside, changing one line and marking it with a MUTATION PROBE comment, running that test, checking that it fails on its own assertion, then restoring the file and seeing it pass. A few of them:

return rate.amount -> return base                 'charges the selected rate'
                                                   expected +0 to be 599
'$' anchor dropped from the fromMajor pattern      'rejects input that is not a decimal amount'
                                                   expected function to throw an error, but it didn't
padStart(exponent + 1) -> padStart(exponent)       'formats each exponent'
                                                   expected '.05' to be '0.05'
Enter fullscreen mode Exit fullscreen mode

All 12 held up. One mutant made the free-shipping hint compare the subtotal with the threshold, and with the whole file running only shows no hint for an empty cart failed while the other six tests stayed green, so that one test is all that holds the empty-cart rule. Another removed the precision check from the library's parser, and besides the library's own test, a storefront test in the other repository failed too, which is the kind of cross-boundary check a review would otherwise have to take on faith.

By hand this is slow and, with an agent doing it, token-heavy too, so for anything bigger I'd put a tool in the gate. StrykerJS with the Vitest runner, with mutate pointed at the changed files, generates the mutants and records which tests killed each one. It counts any failing test as a kill (a TypeError included), so the failure messages are still worth a look, and the hand version stays useful for cases a tool can't express, like the library change that should break a storefront test.

Making it stick with agents

Telling an agent to "write tests first" is easy, and it'll tick the box. What we put in place in that workflow was turning both practices into evidence that something checks:

  • the shared agent rules say tests come first and every new or changed test is proven able to fail before it's committed;
  • each mutant goes into the plan's log with its failure message, not just a tick, and a red step's failure message counts as evidence the same way;
  • the checkpoint step lists every test with no evidence yet, and the pre-PR review treats any test still unproven as a P1 finding, which blocks the PR.

That count matters most, since the review in that feature said every test had a recorded kill while the log had 9 of 21, and only a check that counts would have caught it.

Summary

When we don't read the code, the tests are the review, and a passing suite is only as good as the evidence that each test can fail, so we should ask for that evidence the same way we ask for a green build. Write the tests first from the spec, stub the new code so the red step fails on the assertion, mutate whatever didn't get a real red step, and keep the failure messages somewhere a reviewer (or the next agent) can read them. None of this is new, but with an agent doing most of the work it costs us very little, and it's the only way I've found to trust a green suite I didn't write myself.

Top comments (0)