Writing tests that agents can trust

The faster agents write code, the less possible it is for people to check it line by line. Handing work to agents with confidence takes tests that produce evidence, and a way to test the tests themselves.

When I run a dozen agents at once, I can’t read every diff line by line. If I had to check every change myself, I could keep only one or two agents going. To hand over more work, the human job has to change: define what “done” means beforehand, and review the evidence afterward.

That evidence comes mainly from tests. So which tests deserve an agent’s trust, and mine?

In a recent article, Addy Osmani describes how the Claude Code team approaches verification. About 90% of that team’s code is written and reviewed by Claude, and the article recommends three kinds of tests: end-to-end (E2E), property and differential. I agree, but I think a fourth is needed, one the article doesn’t discuss: mutation testing. The first three test the code. Mutation testing tests the tests.

Bad tests teach agents bad habits

Agents adjust to feedback, and tests are one of their main sources of it, so flaws in the tests turn directly into bad habits in the agent.

When a test passes and fails at random, the agent learns to rerun it rather than fix anything. When tests are slow, it saves up a batch of changes before running them, and a failure is then hard to trace to the change that caused it. So keep everyday feedback fast, and run the heavier tests before committing. When tests cover only the happy path, it starts to treat “the tests pass” as “the feature is correct.” That last habit is the most dangerous, because from the outside everything looks green.

E2E tests: does the feature actually work?

An E2E test walks through a real user flow on a running system, such as adding an item to the cart, checking out and seeing the confirmation page. Osmani’s advice is blunt: “If you have to focus on one test type, pick end-to-end.”

The reason is that such a test is hard to game. Unit tests are faster and more stable, but an agent can make all of them pass and still break the feature, because neither it nor the tests it wrote may understand the whole task. An E2E test asks the question users care about: does this feature work or not?

It is also more useful when it fails. A timeout error leaves the agent guessing. A log of the steps plus a screenshot shows it that the flow stopped at checkout because the payment form never loaded.

So let the agent operate the running system itself. One practical way is to write a verification skill that teaches it how to start, operate and inspect the app, and to require that it runs this before committing.

Property tests: which rules must never break?

An ordinary test gives examples: for this input, expect that output. A property test states a rule: whatever the input, this must hold. A library such as proptest (Rust), Hypothesis (Python) or fast-check (JS/TS) then generates many inputs to try to disprove it.

Four kinds of rules are the most common: round trip, where encoding and then decoding returns the original; invariant, such as an account balance that can’t go negative; idempotency, where retrying any number of times has the same effect as running once; and equivalence, where an optimized implementation returns the same result as a simple, correct one.

A round trip takes only a few lines with proptest:

use proptest::prelude::*;

proptest! {
    #[test]
    fn decode_reverses_encode(input in any::<Vec<u8>>()) {
        let decoded = decode(&encode(&input)).expect("decode failed");
        prop_assert_eq!(decoded, input);
    }
}

By default proptest requires 256 passing cases and Hypothesis runs 100 (actual execution counts vary a little). For critical rules, that can be raised to several thousand or more.

Property tests work especially well with agents. The examples an agent writes often share the blind spots of the code it wrote, and generated inputs can expose some of them. The rule and the generator can carry the same assumptions, though, so a person should define both the rule and the range of inputs, or at least review them.

Differential tests: the old system has the answers

In a rewrite or a migration, the spec has often drifted from what production actually does, and the old system becomes the most reliable reference. A differential test gives the same inputs to both systems and compares the outputs:

for case in random_inputs() + sample(production_traffic):
    old = legacy.handle(case)
    new = rewrite.handle(case)
    # same as the old system, unless a new output was approved
    expected = approved_changes.get(case, old)
    if normalize(new) != normalize(expected):
        report(case, old, new)

Inputs can be generated at random or sampled from production traffic. Sampled traffic must be anonymized first, and replaying it must not cause real side effects. normalize removes differences that don’t matter, such as whitespace.

Intended changes have to be recorded, and what gets recorded must be the expected new output. If the record says only “this input may differ,” then however wrong the new system is on that input, it will never be reported again. With the new output on record, even a change that was approved but never made gets caught.

Mutation testing: who tests the tests?

All three kinds of tests leave the same question open: when every test passes, is the code correct, or do the tests check nothing?

Mutation testing answers by breaking the code on purpose. A tool introduces one small error at a time, producing a “mutant,” and runs the tests. If a test fails, the error was caught. If they all still pass, it was missed. That often means some behavior is checked by no one, with one exception to watch for: some changes don’t affect what the program does, and these are called equivalent mutants.

Here is a simplified example: only editors can publish a post, and only a draft can be published.

fn can_publish(user: &User, post: &Post) -> bool {
    user.is_editor && post.status == Status::Draft
}

#[test]
fn editor_can_publish_a_draft() {
    assert!(can_publish(&editor(), &post(Status::Draft)));
}

The test is green. But cargo-mutants makes four changes to this function:

  • Replace && with ||: missed. With an editor and a draft both conditions hold, so the result is still true.
  • Replace == with !=: caught.
  • Replace the whole body with false: caught.
  • Replace the whole body with true: missed. That is exactly what the test expects.

In other words, this test wouldn’t fail even if anyone at all could publish. It checks only “can” and never “cannot.” One negative test catches both missed mutants:

#[test]
fn non_editor_cannot_publish() {
    assert!(!can_publish(&reader(), &post(Status::Draft)));
}

That still doesn’t make the tests complete. If someone deleted the condition post.status == Status::Draft entirely, both tests would still pass, and that change happens not to be among the four the tool generates. So a third test is needed:

#[test]
fn editor_cannot_publish_twice() {
    assert!(!can_publish(&editor(), &post(Status::Published)));
}

Mutation testing can expose gaps in tests. It can’t prove that there are none. It is a lead, not a score. The same goes for closing the gaps: don’t write a test to kill a particular mutant, write one for behavior that users or callers depend on.

Putting mutation testing in CI

Mutation testing is slow, since every mutant needs a build and a test run. My team keeps both the scope and the cost bounded:

  • Mutate only the Rust code a PR changed (cargo mutants --in-diff pr.diff, where pr.diff is the diff against the base branch), skipping generated code, program entry points and adapters that need a real database.
  • Run at most 60 mutants, about 40 minutes, and sample when there are more.
  • Run one at a time on a machine with 4 vCPUs and 8 GiB, because parallel builds run out of memory.
  • Post the results as a single PR comment, updated on every push, without blocking the merge.

In one real run, 46 of 91 mutants were sampled in about 9 minutes: 19 were caught, none were missed, and the other 27 didn’t compile, so they said nothing about the tests. An earlier run on the same PR had missed two, and the author added two tests for them.

In the report, act on missed mutants and unexplained timeouts. For a missed mutant, first ask whether it changes behavior that must hold. If it does, add a test for that behavior. If it doesn’t, for example because it affects only log output, it can stay, or be excluded precisely with #[mutants::exclude_re] and a written reason. #[mutants::skip] skips the whole annotated function or item, so use it only when that is the intent. For a timeout, check the log and the time limit to tell an infinite loop from a problem with the run itself. And with sampling, “none missed” holds only for the sample.

Don’t let agents edit their own exams

Good tests also have to be protected from being bypassed. Several of the Claude Code team’s practices are worth borrowing.

A change can’t edit the checks that judge it. Read the rules from the main branch, not from the branch under review. Otherwise the shortest path to passing a check is to edit the check.

When fixes keep failing, hand over to a person. Their limit is three rounds.

Don’t hide flaky tests behind waits and retries. Look for the root cause first. If none can be found, delete the test and write down why.

Observe a new gate before enforcing it. First only log what it would have blocked, and enforce it once the false positives are acceptable. Our mutation testing is at the observing stage.

Where to start

The four kinds of tests answer four different questions. E2E: does the feature work for users? Property: does it hold for inputs nobody thought of? Differential: does the new system behave like the old one? Mutation: if the code were wrong, would the tests notice?

They don’t have to arrive all at once. My team uses E2E and mutation testing today, has just started trying property tests, and hasn’t used differential tests yet. If I were starting now, I would ask three things of every PR:

  1. Prove that it runs. Run the affected E2E scenarios and attach the results to the PR.
  2. Respond to the mutation report. For each missed mutant, add a test or explain why not.
  3. Write rules, not just examples. For parsing, money, IDs and retries, add a property test next to the example tests.

That is also why, in Hiring engineers in the age of AI, I listed designing tests among the most important abilities: agents can write the code, but what counts as done, and what evidence is enough to believe it, are for people to decide.

← All posts