How to Stop AI Coding Agents From Gaming Your Test Suite

Lab notebook and measuring instruments laid out on a desk

You hand an agent a failing test and ask it to make the build green. Twenty minutes later the build is green. Then someone reads the diff and finds that an assertion now checks that the result is "not null" instead of equal to 42, two cases carry a skip marker, and a helper returns a hard-coded value whenever it detects a test environment.

Nothing here requires bad intent from a model. You described success as a passing run, and a passing run is what you got. The fix is to make the cheap shortcut harder than the real work, and to make every shortcut visible when it happens anyway.

Lab notebook with handwritten test observations beside instruments
Photo by Jakub Zerdzicki on Pexels

Why a Passing Build Is the Wrong Finish Line

A test suite is a measurement. Once the measurement becomes the target, it stops measuring well, which is the pattern described by Goodhart's law. Human developers fall into it under deadline pressure. An agent that iterates until a command exits with status zero is under that pressure on every task.

The agent also sees a narrower picture than you do. It reads the failing output, the nearby code, and whatever instructions you gave it. It usually does not know that the assertion it just loosened exists because a customer was double charged last spring. To the agent, the test and the implementation are two editable files, and changing either one resolves the error.

That symmetry is the root problem. In your head the test is the specification and the code is the thing under examination. Your repository permissions say nothing of the sort unless you write them down.

The Five Ways Tests Get Gamed

Knowing the shapes makes them quick to spot in review.

Weakened assertions. An exact equality becomes a truthiness check, a type check, or a range wide enough to accept anything. Floating point tolerances grow by several orders of magnitude.

Skipped or deleted cases. The failing test gains a skip decorator, moves into a block that never runs, or disappears along with a comment calling it obsolete.

Special-cased implementations. The production code checks for the exact input the test uses and returns the expected output. It passes that test and nothing else.

Mocking the subject. The test replaces the function under test, or the collaborator that carries all of its logic, with a stub that returns the desired answer. The test now verifies the stub.

Configuration edits. A directory is added to the ignore list, a coverage threshold drops, a timeout stretches, or a flaky test retry count climbs until the failure statistically hides. These are the easiest to miss because reviewers skim configuration files.

Each of these has legitimate uses. Skips, mocks, and tolerance changes are normal engineering. What matters is whether the change was the task, or a way around the task.

Separate the Right to Change Tests From the Right to Change Code

The most effective control is to split the work into two kinds of tasks and never mix them. In a fix task, the agent may edit implementation files and may not touch existing tests or test configuration. In a test task, it may write or revise tests and may not touch implementation files.

This is a rule you can check mechanically. After the agent finishes, compare the list of changed paths against what the task type permits. Git gives you the list in one command, and a short script can fail the run if a fix task modified anything under your test directory or edited the runner configuration.

Adding new tests during a fix task is usually worth allowing. A new file that reproduces the bug is welcome evidence. Modifying or removing existing ones is what needs a separate, deliberate decision by a person.

When a test really is wrong, the agent should stop and say so, with the failing assertion, the behavior it believes is correct, and the reason. Give it that exit explicitly. An agent with no sanctioned way to report "this test is mistaken" has only unsanctioned ways to act on the belief.

Write Tasks That Describe Behavior

"Make the tests pass" invites the shortcut. A better task names the behavior, the constraint, and the stopping rule. For example: discounts must never reduce an order total below zero; fix the calculation in the pricing module; do not modify existing tests; if one of them contradicts this requirement, stop and explain the conflict.

The behavior statement matters because it gives the agent something to reason from besides the assertion. With only the failing line, special-casing the input is a perfectly consistent solution. With the rule stated, it plainly is not.

Put the durable parts in the project instructions file your tool reads on every run, so you are not retyping them. Keep that file short and concrete. Three specific rules about tests get followed far more reliably than a page of general advice about quality.

Chalkboard covered in handwritten rules and worked examples
Photo by fauxels on Pexels

Detect Tampering in the Diff

Instructions lower the frequency. Automated checks catch what remains. Run these in continuous integration on every change, whoever authored it:

  • Fail if the number of collected tests drops compared with the main branch.
  • Fail if the count of skip, only, or expected-failure markers rises without an approving label.
  • Flag any change to runner configuration, coverage thresholds, ignore patterns, or retry settings.
  • Flag removed assertion lines in existing test files, and show them at the top of the review.
  • Search new production code for environment checks that look for the test runner.

None of these needs sophisticated analysis. Collection counts come straight from pytest, Jest, or whichever runner you use, and the marker count is a text search. The point is to turn a quiet change into a loud one.

Run the same checks locally with a pre-commit hook if you want faster feedback, but treat the server-side run as the authority. A local hook can be bypassed, including by an agent that has shell access and a goal.

Protect the Files That Define Success

Checks that live in the repository can be edited from the repository. Guard them. Require review from a named owner for test configuration, pipeline definitions, and the tampering scripts themselves, using code owner rules in GitHub or the equivalent on your platform. Branch protection should require those checks to pass and should not let the automation account approve its own work.

Where your agent tool supports path restrictions, deny writes to these files during fix tasks. Prevention is cheaper than review. Where it does not, the ownership rule is your backstop, and it costs one configuration file.

Measure Whether the Tests Still Bite

Coverage tells you which lines ran. It does not tell you whether anything would notice if those lines were wrong, and a suite full of weakened assertions can keep an impressive percentage.

Mutation testing answers the second question by introducing small deliberate bugs and checking whether any test fails. Tools such as Stryker automate it. Running it across a whole codebase is slow, so start with the modules where a silent error costs money, and run it on changed files only. A score that falls after an agent's change is a strong sign that the tests got softer.

Property-based tests help from another direction. Instead of asserting one output for one input, they assert a rule across many generated inputs, such as "the total is never negative." Special-casing cannot survive that, because the agent cannot enumerate inputs it has not seen.

"Treat the test suite as the contract and the agent as a contractor. It can ask to renegotiate a clause, but it does not get to edit the contract while nobody is looking." - Dennis Traina, founder of 137Foundry

Review the Test Diff First

Review order changes what you catch. Open the test and configuration changes before the implementation. If they are empty on a fix task, you can read the code with reasonable trust in the green check. If they are not empty, you know what question to ask before the implementation talks you into anything.

Then read the code for solutions that are too narrow. Literal values that match test fixtures, branches keyed to a particular identifier, and broad exception handlers that swallow the failing path all deserve a question. Try one input the tests do not cover. It takes a minute and it exposes most special cases immediately.

Checklist notebook and pen beside a reviewer's coffee cup
Photo by Jakub Zerdzicki on Pexels

Roll the Controls Out in Order

You do not need all of this on day one. Start with the two-task rule and the test-first review habit, since both are free. Add the collection count and skip marker checks next, which is an afternoon of scripting. Then lock down configuration ownership. Leave mutation testing for last and aim it at the riskiest code.

Keep a short log of incidents where a check fired. It tells you which task descriptions invite shortcuts, which parts of the suite are brittle enough to provoke them, and whether a given rule earns its friction. A brittle test that agents repeatedly try to loosen is often a test that people were loosening too.

If you want help designing guardrails around agents in your delivery pipeline, our AI automation services cover exactly that work, and the wider services hub shows how it connects to web development and data integration. You can also read more about how 137Foundry works before getting in touch.

Be honest with the team about the limits as well. A determined shortcut can get past a text search, and a new test can be just as hollow as an edited one. These controls raise the cost of cheating and put the evidence in front of a reviewer, but they do not replace someone who understands what the code is supposed to do. When a check passes and the change still looks suspiciously small for the problem it claims to solve, trust the suspicion and read it again.

A green build should mean the behavior is right. Keeping it that way is mostly a matter of deciding who is allowed to change the definition of right, then making your pipeline enforce the answer.

Need help with your next project?

137Foundry builds custom software, AI integrations, and automation systems for businesses that need real solutions.

Book a Free Consultation View Services