How to Add Tests to Old Code With AI (Without Changing What It Does)
Have AI write tests that pin down what the old code does today, run them until they pass on the code as it is, and only then start changing it. The tests become your safety net. Any change that alters behaviour fails a test before it reaches users. It's the first thing we set up with you on a codebase nobody wants to touch.
Start where it hurts
Pick the module that changes most often and breaks most often. Tests there pay off first.
Record what it does now
Have AI call the code with real inputs and record what comes back, including the odd results. Those recordings become the tests.
Make them pass on the code as it is
Run the tests against the untouched code. Every test should pass. If one fails, the test is wrong, not the code.
Test what users would notice
Favour tests that go through the code the way the app uses it, over tests of tiny internal pieces. Those survive the cleanup that comes next.
Then change the code
Refactor in small steps and run the tests after each one. A failing test means behaviour changed, so check whether you meant it to.
What goes wrong
| What you see | Why | Fix |
|---|---|---|
| Tests fail on day one | They describe what the code should do | Pin down what it does today |
| Tests break on every refactor | They test internal details | Test through how the app uses it |
| A bug got "fixed" by accident | Behaviour changed without a decision | Fix bugs on purpose, with a test |
| Coverage everywhere, safety nowhere | Started with the easy parts | Start where it changes and breaks most |
Set it up with us
We'll put tests around the parts of your codebase that break most, with you, so your team can change them without fear.
Questions
Should tests for old code check what it should do or what it does?
What it does today, bugs included. Those tests tell you when a change alters behaviour. Fix bugs after, on purpose.
Where should I start adding tests in an old codebase?
The parts that change most often and break most often. Tests there pay off first.
Can AI write tests for code it doesn't understand?
Yes, if it runs them. Have it call the code with real inputs, record the outputs, and turn those into tests.