AI is good at writing tests for legacy PHP, as long as you ask for the right kind of test. Don’t ask it what the code should do. Ask it to pin down what the code does today, run those tests against the real code, and keep only what passes. Those are characterization tests, and they’re the safety net you need before you touch old code.
The trap is simple. Ask a model to “write unit tests for this function” and it will often write tests for the function it imagines, not the one in front of it. Half fail, someone “fixes” the code to match, and now you’ve changed production behaviour without meaning to. This post walks through a workflow that avoids that, using a small legacy pricing function and a PHPUnit suite you can run yourself.
What this post covers
- Characterization tests, not specification tests
- The legacy function
- The prompt that works
- Running and reviewing what comes back
- Checking the tests actually bite
- Review checklist
- FAQ
Tested on PHP 8.4.27 and PHPUnit 12.5.43. The suite below has 16 tests, all passing against the unchanged legacy code, and each of five deliberate one-line changes to the function makes at least one test fail.
Characterization tests, not specification tests
A specification test says “orders over 1000 get 15% off” because a requirement says so. A characterization test says “an order of 1001 currently returns 850.85” because that’s what happened when you ran it. The second kind doesn’t care whether the behaviour is right. It only records it, so that when you refactor, any change in output shows up as a red test instead of a support ticket.
That framing is what makes AI useful here. Guessing intent from messy code is hard, for people and models alike. Enumerating branches and edge inputs is mechanical, and models are fast at it. Your job moves from typing test cases to judging them.
The legacy function
Here’s the kind of code that usually has no tests: a procedural function, loose comparisons, discounts layered in an order nobody wrote down.
<?php
// Untouched legacy code. Nobody remembers why half of this is here.
function calc_order_total($items, $type, $coupon = null)
{
$total = 0;
foreach ($items as $i) {
if (!isset($i['qty'])) $i['qty'] = 1;
$total += $i['price'] * $i['qty'];
}
if ($type == 'wholesale') {
if ($total > 1000) {
$total = $total * 0.85;
} else {
$total = $total * 0.9;
}
} elseif ($type == 'staff') {
$total = $total / 2;
}
if ($coupon) {
if (strtoupper($coupon) == 'SAVE10') {
$total = $total - 10;
} elseif (substr($coupon, 0, 4) == 'PCT-') {
$total = $total - ($total * intval(substr($coupon, 4)) / 100);
}
}
if ($total < 0) $total = 0;
return round($total, 2);
}
Even this short function has questions hiding in it. Is a negative quantity allowed? Is the coupon prefix case-sensitive? Does the wholesale threshold include exactly 1000? You don’t need the answers before you write tests. The tests will tell you what the answers are right now.
The prompt that works
Give the model the function, the PHP and PHPUnit versions, and very clear rules about what kind of test you want. This is the prompt I’d start from:
You are writing characterization tests for legacy PHP code.
Goal: record what the code does today, not what it should do.
Rules:
- PHP 8.4, PHPUnit 12, attributes (#[DataProvider]), no annotations.
- Do not change the function under test.
- One test per branch: customer types, both wholesale tiers,
each coupon path, the floor at zero, rounding.
- Add edge inputs: missing keys, empty input, string numbers,
negative values, the exact boundary of every comparison.
- Where behaviour looks like a bug, still assert the current output
and add a comment saying it looks unintended.
- After the tests, list each expected value you were unsure of.
Code:
<paste the function here>
The last rule matters most. A model will happily invent an expected value. Asking it to list the ones it’s unsure of tells you where to look first when you run the suite.
Running and reviewing what comes back
Run whatever comes back before you read it closely. Every failing test is one of two things: the model predicted the output wrong, or it found something odd. In both cases the fix is the same. Check the real output, decide whether it’s intended, and set the expectation to what the code actually returns. Never edit the legacy function to make a generated test pass. That isn’t a test any more, it’s a behaviour change.
After review, the suite for this function looks like this:
<?php
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
require_once __DIR__.'/../src/legacy_pricing.php';
// Characterization tests: they pin what calc_order_total() does today,
// not what it should do. Change an expectation only on purpose.
final class CalcOrderTotalTest extends TestCase
{
public static function retailCases(): array
{
return [
'single item, qty given' => [[['price' => 25, 'qty' => 2]], 50.0],
'missing qty counts as 1' => [[['price' => 25]], 25.0],
'several lines add up' => [[['price' => 10, 'qty' => 3], ['price' => 5]], 35.0],
'empty order' => [[], 0.0],
];
}
#[DataProvider('retailCases')]
public function test_retail_totals(array $items, float $expected): void
{
$this->assertSame($expected, calc_order_total($items, 'retail'));
}
public function test_wholesale_gets_10_percent_at_or_below_1000(): void
{
$this->assertSame(900.0, calc_order_total([['price' => 1000]], 'wholesale'));
}
public function test_wholesale_gets_15_percent_above_1000(): void
{
$this->assertSame(850.85, calc_order_total([['price' => 1001]], 'wholesale'));
}
public function test_staff_pay_half(): void
{
$this->assertSame(12.5, calc_order_total([['price' => 25]], 'staff'));
}
public function test_unknown_customer_type_is_treated_as_retail(): void
{
$this->assertSame(25.0, calc_order_total([['price' => 25]], 'vip'));
}
public function test_save10_is_case_insensitive_and_applied_after_type_discount(): void
{
$this->assertSame(2.5, calc_order_total([['price' => 25]], 'staff', 'save10'));
}
public function test_percentage_coupon(): void
{
$this->assertSame(80.0, calc_order_total([['price' => 100]], 'retail', 'PCT-20'));
}
public function test_percentage_prefix_is_case_sensitive(): void
{
// Current behaviour: 'pct-20' is ignored. Looks like a bug, pinned anyway.
$this->assertSame(100.0, calc_order_total([['price' => 100]], 'retail', 'pct-20'));
}
public function test_percentage_coupon_over_100_floors_at_zero(): void
{
$this->assertSame(0.0, calc_order_total([['price' => 100]], 'retail', 'PCT-150'));
}
public function test_unknown_coupon_is_ignored(): void
{
$this->assertSame(100.0, calc_order_total([['price' => 100]], 'retail', 'FREESHIP'));
}
public function test_negative_quantity_reduces_the_total(): void
{
// Current behaviour, not a requirement. Flag for the product owner.
$this->assertSame(75.0, calc_order_total([['price' => 100], ['price' => 25, 'qty' => -1]], 'retail'));
}
public function test_string_prices_are_coerced(): void
{
$this->assertSame(19.98, calc_order_total([['price' => '9.99', 'qty' => '2']], 'retail'));
}
public function test_rounding_happens_once_at_the_end(): void
{
$this->assertSame(0.3, calc_order_total([['price' => 0.1], ['price' => 0.2]], 'retail'));
}
}
A few things worth noticing. The retail cases sit in a PHPUnit data provider, so adding a case is one line. The two tests with comments are the interesting ones: a lowercase pct-20 coupon is silently ignored, and a negative quantity lowers the total. Both look like bugs. Both are pinned anyway, because changing them is a product decision, not a refactor. Write them down and take them to whoever owns pricing.
Also check that every expected value is exact. assertSame(850.85, ...) fails if the function ever returns 850.8500000001. That’s what you want for money. If a generated test uses assertEquals with a delta on a price, ask why.
$ vendor/bin/phpunit tests --testdox
...
OK (16 tests, 16 assertions)
Checking the tests actually bite
Green tests prove nothing until you’ve seen them go red. A generated suite can pass and still miss whole branches, for example by asserting on an order too small to reach the wholesale tier above 1000. Before you trust it, break the code on purpose, one line at a time, and make sure something fails:
| Change made to the legacy function | Tests that failed |
|---|---|
| Wholesale rate above 1000 changed from 0.85 to 0.8 | 1 |
Threshold changed from > 1000 to >= 1000 | 1 |
strtoupper() removed from the SAVE10 check | 1 |
| Floor at zero removed | 1 |
Final round() removed | 11 |
Every change was caught. If one had slipped through, that’s the missing test, and it’s a good follow-up prompt: “This mutation survived; write the test that kills it.” Mutation testing tools like Infection automate this on bigger codebases, and branch coverage from Xdebug or PCOV shows which lines no test reaches. On a single function, a few manual changes are enough.
Once the net is in place, refactor in small steps and rerun after each one. Pull the discount rules into named functions, add types, fix the formatting. On formatting, run your fixer on the new code only at first. I covered setting that up so it doesn’t start arguments in Coding Standards Without Arguments: Pint, PHP-CS-Fixer and CI. If the legacy code calls external APIs, fake them first. Testing External APIs in Laravel with Http::fake shows how in a Laravel app.
Review checklist
- Every expected value comes from running the real code, not from the model’s guess.
- The function under test is unchanged in the same commit as the tests.
- Every comparison has a test on both sides of its boundary.
- Odd behaviour is pinned and commented, with a note for the product owner.
- Money uses exact assertions.
- You’ve broken the code at least a few times and watched the suite fail.
- No test depends on the clock, the network or test order.
- Test names describe behaviour, so a failure reads like a sentence.
For the wider rules on where AI fits in a team’s workflow, such as reviews, ownership and what not to paste into a model, see AI-Assisted Software Development: A CTO’s Guide to Using It Responsibly. If you’re looking at AI for the rest of a web project, the Diligent Creators team has a practical piece on using AI to speed up a web development workflow.
FAQ
Can AI write unit tests for legacy PHP code?
Yes, and it’s one of the better uses of it. Ask for characterization tests that record current behaviour, run them against the real code, and correct any expected value the model got wrong. Treat the output as a draft that you review, not a finished suite.
What is a characterization test?
A test that captures what existing code does right now, whether or not that’s correct. It protects you during refactoring: if behaviour changes, a test fails, and you decide whether the change was intended.
What should I do when an AI-generated test fails?
Check the real output first. If the model guessed wrong, update the expectation. If the output looks like a bug, keep the current value, comment it, and raise it separately. Don’t change the legacy code to match the test.
Is high coverage enough to trust the tests?
No. Coverage shows a line ran, not that a test would notice if it changed. Break the code on purpose, or use mutation testing, and confirm the suite fails.
I’m Shahrukh Akhtar (Shaz3e), CTO & Co-Founder of Diligent Creators Pvt. Ltd., a Technology Executive & Product Builder. I run client delivery and build SaaS products, including EloSync. You can find me on X, LinkedIn, Peerlist and GitHub.
