DEV Community

Cover image for Your AI-Written Tests Pass. Would They Catch a Bug?
Mitar
Mitar

Posted on Edited on

Your AI-Written Tests Pass. Would They Catch a Bug?

Disclaimer: The ideas in this post apply to any language that has a mutation testing tool. The code examples use C#, xUnit, and Stryker.NET because that's the stack I'm most familiar with. If you work elsewhere, PIT does this for Java, mutmut for Python, and StrykerJS for JavaScript and TypeScript.

Here's a pull request I would have approved without thinking twice.

A shipping cost calculator, generated by an AI assistant from a two-line prompt. Alongside it, four unit tests, also generated. All green. The coverage report says 100% line coverage and 100% branch coverage. The diff is small, the names are clear, and nothing about it looks wrong.

Two bugs could slip into that code tomorrow and the test suite wouldn't notice either of them.

You can find them by reading carefully, if you know what you're looking for. Most of us, reviewing the fifth AI-generated pull request of the day, don't. That's the reason I've started treating "the tests pass" as the beginning of a review instead of the end of it.

The problem with one tool writing both the code and the tests

In my last post on code quality, I ended on a question I think every reviewer should ask: would this test fail if the bug we're worried about came back?

I still think that's the right question. The annoying part is that it's hard to answer by reading. You have to imagine the bug, apply it in your head, and then trace through every test to see whether one of them trips. Nobody does that for every line of a 400-line diff. I certainly don't.

AI-generated tests make this harder in a specific way. When the same assistant writes the implementation and the tests in one go, both come from the same understanding of the problem. If the model misread the requirement, the tests encode the same misreading. If it never thought about the boundary, the tests don't touch the boundary. You end up with a suite that agrees with the code, which is not the same as a suite that checks it.

Coverage doesn't help here. Coverage tells you which lines ran while the tests were executing. It says nothing about whether any assertion would have failed if those lines were different. A test that calls a method and asserts nothing at all earns exactly the same coverage as a test that pins down every edge case.

What I want is a tool that does the "imagine the bug" step for me. That's mutation testing.

Mutation testing in two paragraphs

A mutation testing tool makes small, deliberate changes to your production code, one at a time. It flips a >= to a >. It swaps || for &&. It deletes a statement. Each changed version is called a mutant, and for every mutant the tool runs your test suite.

If at least one test fails, the mutant is killed. Your tests noticed. If every test still passes, the mutant survived, which means there's a piece of code whose behavior can change without any test caring. The mutation score is the share of mutants your tests detected.1

The obvious objection is that these are toy bugs. Real bugs aren't a single flipped operator. Fair, and it has been studied. Just et al. took 357 real, developer-fixed faults from five Java projects and found that 73% of them were coupled to simple mutants: a test suite that kills the related mutants tends to catch the real fault too.2 Not all of them. Most. I'll come back to the rest.

The example: a shipping calculator

The prompt was roughly: orders of 50 or more ship free, premium members always ship free, everyone else pays 4.99, reject totals that aren't positive. Here's the code the assistant produced:

public static class ShippingCalculator
{
    public const decimal FreeShippingThreshold = 50m;
    public const decimal StandardRate = 4.99m;

    public static decimal Calculate(decimal orderTotal, bool isPremiumMember)
    {
        if (orderTotal <= 0)
            throw new ArgumentOutOfRangeException(nameof(orderTotal));

        if (isPremiumMember || orderTotal >= FreeShippingThreshold)
            return 0m;

        return StandardRate;
    }
}
Enter fullscreen mode Exit fullscreen mode

Nothing wrong with it. And the tests that came with it:

public class ShippingCalculatorTests
{
    [Fact]
    public void PremiumMember_GetsFreeShipping()
    {
        var result = ShippingCalculator.Calculate(20m, isPremiumMember: true);
        Assert.Equal(0m, result);
    }

    [Fact]
    public void LargeOrder_GetsFreeShipping()
    {
        var result = ShippingCalculator.Calculate(120m, isPremiumMember: false);
        Assert.Equal(0m, result);
    }

    [Fact]
    public void SmallOrder_PaysStandardRate()
    {
        var result = ShippingCalculator.Calculate(20m, isPremiumMember: false);
        Assert.True(result > 0);
    }

    [Fact]
    public void InvalidTotal_Throws()
    {
        Assert.ThrowsAny<Exception>(
            () => ShippingCalculator.Calculate(-5m, isPremiumMember: false));
    }
}
Enter fullscreen mode Exit fullscreen mode

Every line runs. Every if goes both ways at least once, including both sides of the ||. If my review stopped at the coverage report, I'd approve this.

Running Stryker.NET

Stryker.NET installs as a dotnet tool and needs the .NET 8 runtime or newer.3 You run it from the test project's directory:

dotnet tool install -g dotnet-stryker
cd tests/Shop.Core.Tests
dotnet stryker
Enter fullscreen mode Exit fullscreen mode

It builds the solution, runs your tests once unmodified to make sure they pass, then starts generating and testing mutants. When it's done it writes an HTML report with every mutant marked on the source, so you can click through what survived and why.

For this class, most mutants die quickly:

  • || becomes &&: a premium member with a 20 order suddenly pays shipping, and PremiumMember_GetsFreeShipping fails.
  • The throw gets removed: -5 sails through validation, and InvalidTotal_Throws fails.
  • >= becomes <: an order of 120 pays shipping, and LargeOrder_GetsFreeShipping fails.

Two survive:

- if (orderTotal <= 0)
+ if (orderTotal < 0)
Enter fullscreen mode Exit fullscreen mode
- if (isPremiumMember || orderTotal >= FreeShippingThreshold)
+ if (isPremiumMember || orderTotal > FreeShippingThreshold)
Enter fullscreen mode Exit fullscreen mode

Both are boundary bugs. The first lets an order total of exactly zero through validation. The second makes an order of exactly 50.00 pay shipping, which is precisely the kind of bug a customer notices and support then has to explain. The tests use -5, 20 and 120, comfortably away from both edges, so neither change makes anything fail.

This is the part I find useful. Stryker didn't tell me my coverage was bad. My coverage was perfect. It told me which two decisions in this code are unprotected, as a diff I can read in five seconds.

Killing the survivors

The fix is a few tests that sit right on the boundaries:

public static TheoryData<decimal, decimal> ThresholdCases => new()
{
    { 49.99m, ShippingCalculator.StandardRate },
    { 50.00m, 0m },
    { 50.01m, 0m },
};

[Theory]
[MemberData(nameof(ThresholdCases))]
public void FreeShipping_StartsExactlyAtThreshold(decimal total, decimal expected)
{
    var result = ShippingCalculator.Calculate(total, isPremiumMember: false);
    Assert.Equal(expected, result);
}

[Fact]
public void ZeroTotal_IsRejected()
{
    Assert.Throws<ArgumentOutOfRangeException>(
        () => ShippingCalculator.Calculate(0m, isPremiumMember: false));
}
Enter fullscreen mode Exit fullscreen mode

Small detail: this uses TheoryData instead of [InlineData] because C# attribute arguments can't be decimal constants. It's exactly the kind of thing that makes a generated test fail to compile on the first try.

Run Stryker again and both mutants are killed.

Here's the part that's easy to get wrong, especially once you hand this loop to an AI: a surviving mutant is a question, not a bug report. The > version of the threshold check is only wrong because the requirement said "50 or more." If it had said "over 50," the mutant would be the correct code and the original would be the bug. Stryker can't know which one you meant. Neither can the model that wrote the code. Someone has to go back to the requirement and decide.

Letting the AI do the tedious part

I'm not precious about who writes the killing tests. Boundary tests are boring, and a model is fast at them. What changes is the prompt. "Write tests for this class" gets you more tests that agree with the code. Giving it the surviving mutant gets you something better:

This mutant survived mutation testing:

- if (isPremiumMember || orderTotal >= FreeShippingThreshold)
+ if (isPremiumMember || orderTotal > FreeShippingThreshold)

Write a test that passes against the original code and fails against the mutant. If you think the mutated behavior might be what the requirement intended, say so instead of writing the test.

That last sentence matters. Without it, the model will happily write a test that cements whatever the current code does, and that's the problem we started with.

Meta published a paper on a system that takes this idea much further. Their tool, ACH, uses an LLM to generate mutants targeted at a specific concern (privacy regressions, in their case), then uses an LLM to write tests that kill those mutants. In test-a-thons on Messenger and WhatsApp, engineers accepted 73% of the generated tests.4 I find that more convincing than most "AI writes your tests now" claims, because each test is generated against a concrete fault it has to catch, not against a vague request for more coverage.

Putting it in CI without hating your life

Mutation testing is slow. That's the honest downside. Every mutant means another test run, and a real project produces thousands of them. Run the full thing on every pull request and your pipeline gets miserable, and the team turns it off within a week. I would.

Stryker.NET has a few settings that make it bearable. A stryker-config.json in the test project:

{
  "stryker-config": {
    "project": "Shop.Core.csproj",
    "mutate": ["!**/*.Generated.cs"],
    "reporters": ["html", "progress"],
    "thresholds": { "high": 80, "low": 60, "break": 50 },
    "since": { "target": "main" }
  }
}
Enter fullscreen mode Exit fullscreen mode

What these do:5

  • since only tests mutants in code that changed compared to main. That's what turns a long run into something that fits in a normal PR check. On the command line it's dotnet stryker --since:main.
  • thresholds.break makes Stryker exit with a non-zero code when the score drops below that number, and that's what fails the pipeline. The default is 0, so it never fails unless you opt in.
  • mutate with a ! pattern excludes files. Generated code, DTOs, anything where a surviving mutant tells you nothing useful.

I'd start without a break threshold at all. Run it, read the report, kill the survivors that matter, and get a feel for what a normal score looks like in your codebase. Pick a number after that, not before. Setting it to 80 on day one is a good way to teach a team to write tests that kill mutants instead of tests that check behavior, and those aren't always the same thing.

Google's experience is worth knowing here. They surface surviving mutants as code review findings on changed lines, not as a codebase-wide score, and their 2018 paper describes that system being used by around 6,000 engineers.6 A follow-up study covering almost 15 million mutants found that developers who were shown mutants wrote more tests and improved their suites over time.7 The diff-only, review-time approach is the part I'd copy. A big dashboard number for the whole codebase is mostly a way to start arguments.

What it won't catch

I don't want to oversell this.

It only finds the bugs its mutators know how to make. Look back at SmallOrder_PaysStandardRate. It asserts result > 0. If someone changed StandardRate from 4.99m to 499m, that test still passes. Stryker.NET has no mutator for numeric literals,8 so it won't point you at that weak assertion. You still have to read the tests.

Some mutants are equivalent. Sometimes a mutation doesn't change behavior at all, so no test could ever kill it. You'll spend some time on these. Stryker lets you ignore specific mutation types or methods, and you'll end up using that.

It knows nothing about requirements. If the requirement is wrong, or the AI misunderstood it and nobody noticed, mutation testing will help you lock in the wrong behavior very thoroughly. And remember the rest of that Just et al. result: a chunk of real faults wasn't coupled to any simple mutant at all.

It costs compute. Even with since, it's slower than a plain test run. On a large solution, scope it to the projects where the logic actually lives.

Where I'd start

If you want to try this on your own AI-assisted code:

  1. Pick one class with real business logic where both the code and the tests were mostly generated.
  2. Run dotnet stryker against it and open the HTML report.
  3. For each survivor, decide: missing test, equivalent mutant, or unclear requirement?
  4. Write (or prompt for) tests that kill the real ones, then run it again.

My bet is you'll find at least one boundary like the shipping threshold.

The thing I keep coming back to: AI made tests cheap to write, and cheap tests aren't automatically good tests. We used to lean, a little, on the effort it took to write a test as a filter. If someone bothered to write it, they'd probably thought about what it should catch. That filter is gone. Mutation testing is the closest thing I've found to putting it back, and it does it by asking the only question about a test that really matters: would it notice?

Sources

Documentation and papers checked on November 30, 2026. The shipping calculator and the mutants discussed are an illustrative example, derived from Stryker.NET's documented mutators.


  1. Stryker counts killed and timed-out mutants as detected, and survived and uncovered mutants as undetected. Mutants that cause compile errors aren't counted. Mutation score = detected / valid × 100. ↩

  2. 357 real faults and roughly 230,000 mutants across five open-source Java programs. The authors also report that about 17% of the real faults weren't coupled to any mutant, which is the limitation I come back to near the end. ↩

  3. You can also install it per repository with a tool manifest (dotnet new tool-manifest, then dotnet tool install dotnet-stryker), which keeps the version pinned for the whole team. ↩

  4. ACH was applied to 10,795 Android Kotlin classes and produced 571 privacy-hardening tests. The 73% acceptance figure comes from test-a-thons, where engineers also judged 36% of the tests to be privacy-relevant. ↩

  5. All options are described in the Stryker.NET configuration docs. since and with-baseline are mutually exclusive, and with-baseline is still marked experimental. ↩

  6. The system works on code changes during review and processes about 30% of all diffs at Google that have statement coverage calculated. ↩

  7. The same study also used past fixes of high-priority faults to show that mutants are coupled with real faults, which lines up with the Just et al. result. ↩

  8. Stryker.NET mutates operators, boolean and string literals, statements, LINQ methods and more, but not numeric literals. Check the mutations page for the current list. ↩

Top comments (1)

Collapse
 
visionwei profile image
Wei Bin •

Your shipping calculator example landed well — 100% line and branch coverage, yet the >= to > mutant and the zero-total case both survived, which is exactly the kind of boundary slip I see when the same model writes code and tests. I also liked the honesty about SmallOrder_PaysStandardRate: asserting result > 0 would still pass if the rate jumped from 4.99 to 499. Have you found --since:main keeps the run fast enough to use on every PR, or do you still reserve it for logic-heavy changes?