How to Add Tests to Untested Code with AI

Bellwood Primary feeds 640 students a day and pushes about 3,100 lunch orders a week through a PHP app that has never had a single automated test. It was written over four years by a part-time contractor, and in March a routine deploy silently dropped 47 dairy-free orders; nobody caught it until a parent phoned the office.

You cannot retrofit tests onto 4,000 lines in one weekend, but you can cover the paths that hurt when they break in about a week. This workflow uses ChatGPT to rank the risky code, pin today’s behavior, and prove each test actually fails for the right reason before you trust it.

Set the Bar: What “Tested Enough” Means

Testing everything is a fantasy in legacy code. Pick the paths where a silent failure reaches a student, a parent, or the kitchen.

  • Allergen flags: a nut or dairy item must never slip into the wrong tray.
  • Prepayment balances: a balance must never go negative or double-charge.
  • Cut-off times: orders after the daily deadline must be rejected, not queued.
  • Roster import: a malformed CSV must fail loudly, not half-import.

Write that list down before you prompt. Every test you generate should trace back to one of these four, and anything outside the list can wait until next term.

The temptation is to chase line coverage, because a percentage is easy to show a head teacher. Resist it. Covering 80 percent of the report renderer is worthless if the allergen filter is still untested. Aim for coverage of consequence, not coverage of lines.

Work one module at a time, never the whole repo. A single order-handling file gives the model enough context to reason about behavior and keeps each review short enough to actually read. Bellwood’s lunch app is 4,000 lines across nine files; one file a day for a week is a plan, while feeding all nine files into one prompt produces shallow tests that pin nothing a reviewer would care about.

Step 1: Make ChatGPT Map the Risky Paths

Feed the model one module, not the whole repo, and ask it to rank failure modes before it writes anything.

You are a cautious PHP engineer reviewing a legacy school lunch ordering module
that has no tests. Read the code below and produce a risk map.
For each risky behavior give:
1. The function name and line range.
2. What can silently go wrong (not just throwing an error, but returning wrong data).
3. Who is hurt: student, parent, kitchen, or finance.
4. A likelihood x impact score from 1 to 5.
Sort by score, highest first. Do not propose fixes yet. List no more than
eight behaviors, and put anything about allergens at the very top.
Here is the code:
<paste the module here>

What you get: a short, ranked list of the places worth testing first. On Bellwood’s order module the top two were the allergen merge and the balance deduction, which matched the March incident exactly.

Step 2: Capture Current Behavior with Characterization Tests

Legacy code is untested, so you do not yet know what “correct” means. First lock in what the code does today, then decide what it should do.

Write PHPUnit tests that capture the current behavior of the functions below,
even where the behavior looks wrong. Use data providers.
Cover these cases for each function: valid input, boundary input, and one
malformed input.
For every test add a one-line comment stating what behavior it pins, and mark any
test that documents a suspected bug with @todo.
Return only the test file, using this namespace and base class:
namespace App\Tests\Lunch;
use PHPUnit\Framework\TestCase;
Functions to cover:
<paste function signatures and bodies>

What you get: a runnable test file that passes against today’s code. Passing is the point. A characterization test that fails immediately tells you the model guessed the intended behavior instead of reading the actual code.

Run the suite before you change a single line. If any test fails, the model misread the code, so you fix the test, not the application. This order is what keeps the safety net honest.

This step also drags hidden behavior into the light. Expect to find a helper that rounds balances to the nearest penny, or a legacy branch that no one has touched in two years. Pin it anyway. Discovering that a rule exists only after you accidentally break it is the exact failure you are trying to prevent.

Step 3: Turn Suspected Bugs Into Failing Tests

Now reverse the rules. For each @todo case, write a test that encodes the behavior you want, and accept that it will fail.

For each @todo test above, write a replacement test that asserts the correct
behavior instead of the current behavior.
Rules:
- The new test must fail against the current code. Explain in one sentence why
  it fails today.
- List the smallest code change that would make it pass, but do not write that
  change yet.
- Group the failures into a short fix order, safest fix first.
Context: allergen merging must never drop a flagged item, and a balance must never
go below zero.

What you get: a set of red tests that describe the bugs in executable form, plus a fix order. Each red test is a bug report a future developer cannot argue with.

Notice that the fix order matters as much as the tests. Repairing the safest red test first keeps the app working while the suite grows, and it leaves you a runnable checkpoint after every small change instead of one large, risky edit at the end of the week.

Step 4: Prove the Tests Catch Real Breaks

A test that passes for the wrong reason is worse than no test. Break the code on purpose and confirm the suite screams.

I will mutate the code by hand. For each mutation below tell me whether the current
suite should fail, which test should catch it, and what a false pass would look like.
Mutations:
1. Change the allergen merge to overwrite instead of append.
2. Remove the balance floor check.
3. Change the cut-off comparison from greater-than to greater-or-equal.
Then list any risky behavior from the original risk map that no test currently
covers.

What you get: a mutation checklist and a gap list. If swapping the allergen merge to overwrite does not turn the suite red, your most important test is decorative, and you fix that before shipping anything.

This step is the whole point of the workflow. A green suite means nothing until you have watched it go red for the right reason.

Deliverables Before You Call It Covered

  • A ranked risk map of the module, allergens first.
  • A passing characterization test file that pins today’s behavior.
  • A set of red tests that encode the fixes you actually want.
  • A mutation checklist proving the suite catches real breaks.
  • A short gap list of risky paths still untested.
  • The suite wired into CI so a red test blocks the deploy.

Where Adding Tests Goes Wrong

Testing everything at once. On a 4,000-line app this stalls. Start with the path that hurt last time and expand outward.

Asking the model what the code should do. It will invent correct-looking behavior. Pin what the code does first, then decide what it should do.

Trusting a green suite you have never seen fail. Mutate the code and watch it break. If it does not, the test is lying to you.

Letting new tests rot outside CI. A suite nobody runs is a document, not a safety net. Make a red test block the merge.

One failure is quieter than the rest: writing only happy-path tests. The March incident lived on a valid order with a dairy flag, which is a happy path until an allergen is involved. Seed your data providers with the combinations that actually reach a tray, not the tidy ones that make the suite easy to pass. For a narrower worked example, see our unit test prompt, and set the model’s defaults before you start with our TDD settings guide. If the module needs restructuring before it is testable at all, the sequence in our legacy refactor workflow keeps each change small.

Sources & Notes

The risk-map-to-mutation sequence is our own framing of standard legacy testing practice, reviewed on 2026-10-12. Bellwood Primary, its 640 students, and the 47 dropped dairy-free orders are illustrative examples, and the PHP module is representative rather than actual. PHPUnit, CI, and the tooling names are used as common examples and each has its own configuration. Language models change between versions, so re-check any prompt that references your specific framework or test runner.

声明:1.本站所有文章,如无特殊说明或标注,均为本站原创发布。本网站中【文本生成/文生图】使用了DeeSseek人工智能生成内容技术, 算法来源说明:本网站未自行开发、训练或部署深度合成算法,所使用的人工智能算法来自:DeepSeek、Chatgpt、Google Gemini。 2.为了网站加载速度优化,本站预览图片进行压缩处理,所以有些不是太清晰,并不影响AI提示词生图、AI设计等内容。3.任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。--GUUNN.COM