
Learn to Program in the Age of AI, Part 5: Testing as Your Safety Net (2026)
An AI assistant can write a function in seconds. It cannot tell you whether the function is right. Something has to check it, and that something should not be your impression of the code.
Tests are that check. They are small programs that call your code and compare the result with what you expected. When AI writes your code, tests become your safety net. They catch the wrong answer before it ships, and they let you change code without fear.
This is the fifth article in my series for beginners, career switchers, and junior developers who already use AI tools. Part 1 explained which skills still matter. Part 2 covered AI as a tutor. Part 3 gave you a review checklist. Part 4 taught debugging, and ended with a warning: a test that has never failed proves nothing. This part shows how to write tests that can fail, and how to find out whether yours can.
As always, I tested it. I wrote five small functions, each with a weak test suite and a strong one. Then I injected 61 small bugs and counted how many each suite caught. I asked a local AI model to implement the functions from a description alone, from weak tests, and from strong tests. Finally, I asked it to write tests for a buggy function, with and without the specification. The research I cite comes from published papers that I checked on December 1, 2026.
The series
- What still matters
- Using AI as a tutor, not a ghostwriter
- Reading and reviewing AI-generated code
- Debugging without handing everything to the AI
- Testing as your safety net (this article)
- Your first project with an agent
Table of Contents
- The Short Answer
- Why Tests Matter More With AI
- What a Test Is
- A Worked Example: Tests First, Then the AI
- Experiment 1: Measure What Your Tests Catch
- Experiment 2: Tests as the Specification
- Experiment 3: Can the AI Write Your Tests?
- A Test-First Workflow With AI
- Rules for Testing With AI
- Practice: Find the Missing Tests
- Common Mistakes
- Frequently Asked Questions
- Conclusion
- References
1. The Short Answer
Five habits make tests useful when AI writes the code.
| Habit | Why it matters |
|---|---|
| 1. Write the test list before the code | Tests state your intent, which the AI cannot guess |
| 2. Test edges and errors, not only examples | My weak suites covered 87% of lines but caught only 64% of injected bugs |
| 3. Run the tests yourself | Models given the tests still failed some of them |
| 4. Write tests from the spec, not the code | Tests written from buggy code caught the bug 6 times in 15, and locked it in 8 |
| 5. Measure your suite by breaking the code | If a deliberate bug leaves the tests green, a test is missing |
Here is what the three experiments found, using Gemma 4 (gemma4:e4b) running locally.
| Experiment | What I tested | Result |
|---|---|---|
| 1. Mutation testing | Weak and strong suites against 61 injected bugs | Weak caught 39 (64%), strong caught 57 (93%). Line coverage was 87% against 100% |
| 2. Tests as a spec | AI implements from a description, weak tests, or strong tests | Behaviors the strong tests state failed 4% of the time, against 18% and 23% |
| 3. AI-written tests | Tests written from the spec, from the code, or from both | Catch the bug: 14, 6, and 14 of 15. Lock the bug in: 0, 8, and 0 of 15 |
The pattern across all three is the same. A test is a statement of intent, so the quality of the test depends on where the intent came from. Written from your spec, tests protect you. Written from the code, they mostly describe the code.
2. Why Tests Matter More With AI
Part 3 ended on a rule: asking the AI again is not verification. When a model has a gap, every new attempt repeats it. Only an outside check breaks the cycle, and a test is the cheapest outside check there is.
There is also evidence that tests help the model itself. Mathews and Nagappan tested GPT-4 and Llama 3 on standard code-generation benchmarks. Providing test cases along with the problem statement led to higher success rates than the statement alone. Tests are not just for catching mistakes. They are a clear way to say what you mean.
That matters because of the “almost right” problem from Part 1. Stack Overflow’s 2025 survey found that the top frustration with AI tools was solutions that are almost right. Almost-right code passes a quick look and a happy-path example. It fails on the empty input, the boundary, or the error case. Those are the cases a good test list contains.
A second reason is change. You will edit AI-written code, and so will the AI. Each edit can break something that worked. A test suite tells you within seconds, as the worked example below shows.
3. What a Test Is
A test calls your code with a known input and compares the result with the result you expect. If they differ, the test fails and tells you where.
The simplest test is an assert statement, which raises an error if its condition is false.
assert parse_duration("1h30m") == 5400
Python’s built-in unittest module groups tests into methods and reports every failure. It ships with Python, so nothing needs installing.
import unittest
from duration import parse_duration
class ParseDurationTests(unittest.TestCase):
def test_hours_and_minutes(self):
self.assertEqual(parse_duration("1h30m"), 5400)
def test_empty_string_is_an_error(self):
with self.assertRaises(ValueError):
parse_duration("")
Run the file with python -m unittest test_duration. Many developers prefer pytest, which needs less boilerplate. I used unittest and plain asserts, and I did not test pytest.
Three things make a test good.
- It checks one behavior: The name says which one, such as
test_empty_string_is_an_error. - It can fail: If it passes on broken code, it protects nothing.
- It states the expected result in advance: You write the number, not the code that computes it.
The third point is the one people skip. If you compute the expected value by running the code and pasting the output, you have recorded what the code does, not what it should do.
4. A Worked Example: Tests First, Then the AI
I will build a function that converts a duration string such as "1h30m" into seconds. The AI writes the code. I write the tests first.
Step 1: Describe the behavior in words
Before any code, list what the function must do. Include the edges and the errors.
"1h30m"is 5400 seconds, and"45s"and"2h"work on their own."1h1m1s"uses all three units, and"0s"is allowed.- Minutes may be more than 59, so
"90m"is 5400. - An empty string, a number with no unit, an unknown unit, and spaces are all errors.
Step 2: Turn the list into tests
Each line of the list becomes a test.
import unittest
from duration import parse_duration
class ParseDurationTests(unittest.TestCase):
def test_hours_and_minutes(self):
self.assertEqual(parse_duration("1h30m"), 5400)
def test_a_single_unit(self):
self.assertEqual(parse_duration("45s"), 45)
self.assertEqual(parse_duration("2h"), 7200)
def test_all_three_units(self):
self.assertEqual(parse_duration("1h1m1s"), 3661)
def test_zero_is_allowed(self):
self.assertEqual(parse_duration("0s"), 0)
def test_minutes_may_be_more_than_59(self):
self.assertEqual(parse_duration("90m"), 5400)
def test_empty_string_is_an_error(self):
with self.assertRaises(ValueError):
parse_duration("")
def test_number_without_a_unit_is_an_error(self):
with self.assertRaises(ValueError):
parse_duration("90")
def test_unknown_unit_is_an_error(self):
with self.assertRaises(ValueError):
parse_duration("5x")
def test_spaces_are_an_error(self):
with self.assertRaises(ValueError):
parse_duration("1h 30m")
Step 3: See them fail
Before the AI writes anything, run the tests against an empty stub, raise NotImplementedError. This is the “red” step.
Ran 9 tests in 0.004s
FAILED (errors=9)
All nine fail, which is correct. A test that passes against a stub is testing nothing.
Step 4: Ask the AI to implement it
I gave the model a one-sentence description and the same checks, written as plain assert lines. The prompt looked like this.
Write a Python function.
parse_duration(s) converts a duration string like "1h30m" into a number of seconds.
It must pass these tests. The helper raises(exc, fn, *args) returns True if
calling fn raises exc.
(the assert lines went here)
Reply with one code block containing the complete function and any imports it needs.
I ran the unit tests against its answer.
Ran 9 tests in 0.000s
OK
All nine pass, which is the “green” step. Many people stop here.
Step 5: Do not stop at green
Green means the code passes the tests you wrote, not that the code is right. I tried a few inputs that my tests never mentioned.
| Input | What the AI’s code returned | What it should do |
|---|---|---|
"1h30m" |
5400 | 5400 |
"abc5s" |
5 | ValueError |
"5sx" |
5 | ValueError |
"5s6" |
5 | ValueError |
"-5s" |
5 | ValueError |
The code searched the string for pieces such as 5s and added them up, ignoring everything around them. It passed all nine tests because none of them put junk next to a valid piece.
Step 6: Turn each discovery into a test
Each surprise becomes a permanent test.
def test_junk_before_a_valid_part_is_an_error(self):
with self.assertRaises(ValueError):
parse_duration("abc5s")
def test_junk_after_a_valid_part_is_an_error(self):
with self.assertRaises(ValueError):
parse_duration("5sx")
Running the suite again, the code is red.
FAIL: test_junk_after_a_valid_part_is_an_error
AssertionError: ValueError not raised
FAIL: test_junk_before_a_valid_part_is_an_error
AssertionError: ValueError not raised
Ran 11 tests in 0.002s
FAILED (failures=2)
Step 7: Ask for the fix with a bug report
I used the template from Part 4: the minimal case, expected, actual, and what I checked. I pasted the code and asked three times.
Minimal case: parse_duration("abc5s").
Expected: ValueError.
Actual: it returns 5.
What I checked: parse_duration("5sx") also returns 5. The code seems to look for
pieces like "5s" anywhere in the string and ignore everything else.
Two of the three fixes passed all 11 tests. The third looked reasonable, then failed with three errors.
The safety net caught a regression. The third fix rejected bad characters with the check
[\dhm]+, which forgot the letters. Three older tests failed at once:"45s","1h1m1s", and"0s". Without the earlier tests, I would have shipped a parser that rejects every duration containing seconds.
Step 8: Simplify without fear
Both working fixes were long and defensive. A short version exists, which uses one pattern that must match the whole string.
import re
def parse_duration(s):
m = re.fullmatch(r"(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?", s)
if not s or m is None:
raise ValueError(f"bad duration: {s!r}")
hours, minutes, seconds = (int(x) if x else 0 for x in m.groups())
return hours * 3600 + minutes * 60 + seconds
It passes all 11 tests. Because the tests exist, I could replace the AI’s code with something simpler without worrying that I broke it. That is the second job of a test suite: it makes simplifying safe, which answers question 7 of the Part 3 checklist.
5. Experiment 1: Measure What Your Tests Catch
Key result: The weak suites ran 87% of the lines, yet caught only 64% of 61 injected bugs and 0 of 5 realistic ones. The strong suites caught 93% and 5 of 5.
How do you know whether your tests are good? The usual answer is code coverage, the percentage of lines that run during the tests. Coverage is easy to measure, and it is a weaker signal than it looks.
Inozemtseva and Holmes studied this in 2014, using large Java programs and thousands of generated test suites. They found a low to moderate correlation between coverage and how many bugs a suite catches, once suite size is accounted for. Their conclusion was that coverage helps you find untested code, but it should not be a quality target.
A better question is: if I introduce a bug, do the tests notice? That is mutation testing. A tool makes a small change to your code, such as < to <=, and runs the tests. If they still pass, the change “survived”, and your tests have a hole. Google has described using the technique in code review.
The setup
I wrote five small functions, each with a correct version.
| Function | What it does |
|---|---|
parse_duration |
Converts "1h30m" to seconds, and rejects malformed strings |
merge_intervals |
Merges overlapping [start, end] pairs |
median |
Returns the middle value, or the average of the two middle values |
split_bill |
Splits an amount in cents between people, extra cents to the first |
slugify |
Turns a title into a URL slug |
For each function, I wrote two suites. The weak suite is what a beginner, or an AI told to “add some tests”, usually writes first: two or three happy-path examples, 14 tests in total. The strong suite adds boundaries, empty input, and error cases, 44 tests in total.
Then I wrote a short script that injects bugs. It changes one thing at a time: a comparison, an operator, a number up or down by one, a piece of text, a return value, a removed raise, or max swapped with min. It produced 61 mutants. I ran every suite against every mutant, in a separate process with a time limit.
A hole in my own tests
To decide which mutants were real bugs, I also wrote a larger “oracle” suite with extra cases. It missed four mutants, and they were real holes. Three changed merged[-1] to merged[-0] in merge_intervals. One changed strip("-") to strip("-x") in slugify, so a word such as “Linux” lost its last letter. I added three tests, and then all 61 mutants were caught. Mutation testing found gaps in the tests of someone who was paying close attention.
The results
| Function | Injected bugs | Weak suite catches | Strong suite catches | Weak suite line coverage |
|---|---|---|---|---|
parse_duration |
15 | 13 | 15 | 6 of 7 lines |
merge_intervals |
16 | 11 | 13 | 7 of 7 lines |
median |
17 | 7 | 17 | 6 of 8 lines |
split_bill |
9 | 5 | 9 | 4 of 5 lines |
slugify |
4 | 3 | 3 | 4 of 4 lines |
| Total | 61 | 39 (64%) | 57 (93%) | 27 of 31 (87%) |
The strong suites reached 100% line coverage. The weak suites reached 87%, and for merge_intervals and slugify they reached 100% while still missing bugs. Running every line is not the same as checking every line’s result.
The strong suite also missed four mutants, which are the same four that exposed the holes in my oracle. A strong suite is better, not finished.
What the weak suites missed
- Boundaries: Swapping
<and<=survived inmerge_intervalsandsplit_bill, because no test used an input at the boundary. - Error paths: Removing a
raisesurvived in three functions, because no weak test sent bad input. - Whole branches: The weak
mediansuite never used an even-length list, so it caught only 7 of 17 mutants. - Numbers: Changing a constant by one survived often, because the examples were too round.
The realistic bug
Random mutants are mechanical. So I also wrote one realistic bug per function, the kind a person or an AI might actually make.
parse_duration: An empty string returns 0.merge_intervals: Intervals that touch are not merged.median: An even count uses integer division.split_bill: The extra cents go to the last people.slugify: Each symbol becomes its own hyphen.
0 of 5 against 5 of 5. The weak suites caught none of the realistic bugs, and the strong suites caught all of them. The random mutants show the pattern, but this is the result to remember.
What this does and does not show
The numbers come from five small functions and a small mutator, so they are illustrations, not benchmarks. Mutants are mechanical bugs, and real bugs are often subtler. The mutator also depends on the code: slugify produced only four mutants, because most of its logic is inside a text pattern.
What the experiment does show is the shape of the problem. Examples that run every line can still miss most bugs, and the missing tests are boundaries, errors, and unusual shapes of input.
Do it by hand
You do not need a tool. Pick one line in your code and break it on purpose. Change a < to <=, delete a raise, or add one to a number, and then run the tests. If they stay green, you have found a missing test. You can practice this on any function you have written, not only the examples here.
Tools that automate this exist, such as mutmut for Python. I wrote a short script so I did not have to install anything.
6. Experiment 2: Tests as the Specification
Key result: Strong tests cut the model’s failures on the behaviors they state from 18% to 4%. It still failed a test it was shown in 4 of 15 strong-test replies.
If tests state your intent, giving them to the AI should help it implement the right thing. I tested that directly.
How I asked the model
For each of the five functions, I wrote a one-or-two-sentence description, such as “median(nums) returns the median of a list of numbers”. I asked Gemma 4 (gemma4:e4b) to implement each function three ways.
- Description only: just the sentence, with no tests.
- Description plus the weak tests: the sentence and the two or three happy-path examples.
- Description plus the strong tests: the sentence and the full set of edge and error cases.
Each request ran three times, which gave 45 replies. I graded every reply against a hidden suite of 74 assertions. The hidden suite contained the strong tests, plus extra inputs that the model never saw. Copying the visible answers would not have passed.
The scores
| Asked with | Behaviors the strong tests state, failed | Unstated extra cases, failed | Runs passing every hidden test |
|---|---|---|---|
| Description only | 16 of 90 (18%) | 16 of 90 (18%) | 8 of 15 |
| Weak tests | 21 of 90 (23%) | 22 of 90 (24%) | 6 of 15 |
| Strong tests | 4 of 90 (4%) | 5 of 90 (6%) | 9 of 15 |
The model passed an average of 88% of hidden assertions from the description alone, 81% with weak tests, and 96% with strong tests.
Strong tests cut failures on the behaviors they state from 18% to 4%. Weak tests did no better than the description alone. That fits the idea that a test communicates exactly what it contains. A test for "1h 30m" tells the model that spaces are an error. A description that never mentions spaces does not.
Per function, the number of runs that passed every hidden test shows where the strong tests helped and where they did not.
| Function | Description only | Weak tests | Strong tests |
|---|---|---|---|
parse_duration |
0 of 3 | 0 of 3 | 0 of 3 |
merge_intervals |
3 of 3 | 2 of 3 | 3 of 3 |
median |
2 of 3 | 3 of 3 | 3 of 3 |
split_bill |
3 of 3 | 1 of 3 | 3 of 3 |
slugify |
0 of 3 | 0 of 3 | 0 of 3 |
The “every hidden test” count hides the improvement for parse_duration. With a description or weak tests, the model failed 8 of its 18 hidden assertions, all of them error cases. With strong tests, it failed at most one.
In two of the three strong-test runs, the remaining failure was "-5s", an extra case the visible tests never mentioned, which the code accepted. The third run failed "1h 30m", a test it had been shown.
Why two functions stayed stubborn
slugify stayed hard in every condition. In all nine runs, the model deleted punctuation instead of turning it into a hyphen. So "Version 2.0" became "version-20" and "one,two;three" became "onetwothree". That habit overrode even a visible test that demanded "version-2-0".
parse_duration failed for a different reason. The strong tests covered four kinds of bad input, and in two runs the model still accepted "-5s", which nobody had shown it. Tests teach the model only what they contain.
The model did not run the tests
Here is the part that matters most for your habits. When the model was given tests, it still failed some of them. Four of the 15 strong-test replies and one of the 15 weak-test replies failed at least one test that was in the prompt.
For slugify, all three strong-test replies failed the visible check slugify("Version 2.0") == "version-2-0", because the model removed the dot instead of turning it into a hyphen. In two of the five failing replies, the code ended with a line that prints “All tests passed!” Running that code would have raised an AssertionError before reaching it.
A model that is shown the tests has not run them. In 5 of the 30 replies that came with tests, the code failed a test it was shown. Treat “this passes your tests” as a claim, like every other claim in this series, and run the tests yourself.
Limits of Experiment 2
Fifteen runs per condition is a small sample. Eight, six, and nine passing runs out of fifteen are too close to call, and I would not conclude that weak tests make things worse.
The per-assertion numbers are more informative, but a few stubborn cases dominate them. This used one small model, and larger models may behave differently. The direction matches the published result: tests alongside a description help.
7. Experiment 3: Can the AI Write Your Tests?
Key result: Tests written from the spec caught the bug in 14 of 15 suites. Tests written from the buggy code caught it in 6 and locked it in in 8.
The obvious shortcut is to ask the AI for tests too. I tested whether those tests are any good, and whether it matters what the AI sees.
How I asked for tests
For each function, I used the realistic bug from Experiment 1. I wrote a full description of the correct behavior. Then I asked Gemma 4 (gemma4:e4b) for 8 to 12 assert tests in three ways.
- Spec only: the description, and no code.
- Code only: the buggy function, with “write tests for this function”. This is how most people ask.
- Spec and code: both.
Each ran three times, which gave 45 test suites. I ran every assertion against the correct version and against the buggy one. That gives three measurements.
- Catches the bug: at least one assertion passes on the correct code and fails on the buggy code.
- Locks in the bug: at least one assertion fails on the correct code and passes on the buggy code. The test expects the wrong behavior.
- Wrong test: an assertion that fails on the correct code.
My first extractor found no tests in 30 of the 45 replies. The model had skipped the code fence and written bare assert lines. I fixed the extractor after reading the replies, and then all 45 were usable.
What the suites showed
| Tests written from | Catch the bug | Lock the bug in | Suites with a wrong test | Wrong assertions |
|---|---|---|---|---|
| Spec only | 14 of 15 | 0 of 15 | 2 of 15 | 3 of 146 |
| Code only | 6 of 15 | 8 of 15 | 10 of 15 | 32 of 144 |
| Spec and code | 14 of 15 | 0 of 15 | 4 of 15 | 4 of 145 |
Per function, the number of suites that caught the bug shows a clear split.
| Function | Spec only | Code only | Spec and code |
|---|---|---|---|
parse_duration |
3 of 3 | 0 of 3 | 3 of 3 |
merge_intervals |
3 of 3 | 3 of 3 | 3 of 3 |
median |
3 of 3 | 0 of 3 | 3 of 3 |
split_bill |
3 of 3 | 3 of 3 | 2 of 3 |
slugify |
2 of 3 | 0 of 3 | 3 of 3 |
Tests that describe the bug
When the model saw only the code, it often wrote tests that agreed with the code, bug included. These real assertions failed on the correct code and passed on the buggy one.
assert parse_duration("") == 0
assert median([1, 2]) == 1
assert median([1, 100]) == 50
assert split_bill(101, 2) == [50, 51]
The median examples are wrong, since the median of 1 and 2 is 1.5. The buggy code uses integer division, and the model’s tests copied that.
One parse_duration suite also invented an attribute that does not exist and wrote parse_duration("1h").result == 3600. All eight of its checks failed on both versions, and that one suite accounts for 8 of the 32 wrong assertions.
When the model saw the description, it wrote the correct expectations. With spec only, it caught the bug in 14 of 15 suites and locked it in in none. With spec and code, the result was the same.
This is the experimental version of a claim from Part 1. If you write tests after reading the code, you tend to test what the code does, not what it should do. The model does the same.
Give the AI the intent, not just the code. A test is only as independent as its source. Tests written from the code can only agree with the code.
Even good AI tests have gaps
Each spec-based condition caught the bug in 14 of 15 suites, so each missed it once. One slugify suite never used two symbols in a row in the middle of a title, which is the only way the bug shows.
That is why you review AI-written tests with the same suspicion as AI-written code. It is also why Experiment 1’s trick of breaking the code on purpose matters.
Limits of Experiment 3
Fifteen suites per condition is a small sample, and I used one small model. The “code only” condition shows what happens when intent is missing, not that models cannot write good tests. The cleanest finding is the contrast: the same model wrote mostly sound tests from a description and mostly agreeing tests from the code.
8. A Test-First Workflow With AI
Here is a workflow that applies the results of all three experiments.
- Describe the behavior in plain words: Two or three sentences, plus the edge cases and the errors. This is your intent.
- Ask the AI for tests, from the description only: Do not paste code.
- Review and extend the tests: Add the boundaries, empty input, and error cases it missed.
- Run them against a stub: Every test should fail.
- Ask the AI to implement the function: Give it the description and the tests.
- Run the tests yourself: Do not accept “this passes”.
- Read the code: Use the Part 3 checklist, including “is it simpler than it needs to be?”
- Probe with inputs the tests never mentioned: Empty, huge, malformed, and surprising values.
- Turn every surprise into a test.
- Break the code on purpose: If a deliberate bug leaves the tests green, add a test.
The prompt for step 2 can be short.
Here is the specification of a Python function.
(your description)
Write tests for the function. Include boundary cases, empty input, and every
error case the specification mentions. Reply with one code block of assert
statements. Do not write the function.
And the prompt for step 5 can reuse the tests.
Write a Python function.
(your description)
It must pass these tests:
(the tests)
Reply with one code block containing the complete function and any imports it needs.
The order comes from the experiments.
- Step 2 asks for tests from the description only: In Experiment 3, spec-only tests caught the bug in 14 of 15 suites, while code-only tests caught it in 6.
- Step 3 asks you to review them: Even the good suites missed the bug once.
- Step 5 gives the model your tests: In Experiment 2, strong tests cut failures on the behaviors they state from 18% to 4%.
- Steps 6 to 10 are yours: The model still failed tests it was shown, and in the worked example a green suite hid a real bug.
9. Rules for Testing With AI
- Write the expectation first. Decide the expected result before you see any output, so the test records what should happen.
- Never generate expected values by running the code. Pasting its output into a test records its behavior, bugs included.
- Give the AI the spec, not only the code. Tests written from code mostly agree with the code.
- Run the tests yourself. A model can show a line that prints “All tests passed!” without having run anything.
- Test boundaries and errors. Both sides of every limit, the empty case, and every input that should be rejected.
- Do not chase coverage. A suite can run every line and still miss most bugs.
- Break your code on purpose. One deliberate bug is a quick test of your tests.
- Turn every bug into a test. Part 4 already said it: keep the failing case so the bug cannot come back unseen.
10. Practice: Find the Missing Tests
Exercise 1
This function sets the shipping cost by weight. Orders under 2 kg cost 5.00. Orders from 2 kg up to, but not including, 10 kg cost 8.00. Orders of 10 kg or more cost 12.00.
def shipping_cost(weight_kg):
if weight_kg < 2:
return 5.00
if weight_kg < 10:
return 8.00
return 12.00
Here are the tests, and they all pass.
assert shipping_cost(1) == 5.00
assert shipping_cost(5) == 8.00
assert shipping_cost(15) == 12.00
Someone changes weight_kg < 2 to weight_kg <= 2. Another person changes weight_kg < 10 to weight_kg <= 10. The three tests still pass. Which tests would you add so that both changes are caught?
Exercise 2
Write the tests first, before any code exists. A function format_minutes(total) turns a number of minutes into text. Under an hour, it returns "45m". From one hour up, it returns hours and two-digit minutes, such as "2h05m". Zero gives "0m", and a negative number raises ValueError.
Write at least six tests before you write, or ask for, any code. Include one case where a common mistake would show up.
Answers
Exercise 1 answer
Add tests on both sides of both boundaries.
assert shipping_cost(1.99) == 5.00
assert shipping_cost(2) == 8.00
assert shipping_cost(9.99) == 8.00
assert shipping_cost(10) == 12.00
I ran these against all 9 mutants my script produced for the function. The three original tests let 5 of them survive. With only the boundary values 2 and 10 added, one survived, a change from 10 to 9 that is only visible just below the boundary. With both sides of both boundaries, none survived. A boundary needs a test on each side.
Exercise 2 answer
Here is a suite that works.
assert format_minutes(0) == "0m"
assert format_minutes(45) == "45m"
assert format_minutes(59) == "59m"
assert format_minutes(60) == "1h00m"
assert format_minutes(125) == "2h05m"
assert format_minutes(600) == "10h00m"
assert raises(ValueError, format_minutes, -1)
I checked these against a correct implementation and against two common mistakes. If the code forgets the zero padding, the tests for 60, 125, and 600 fail. If it forgets the short form under an hour, the tests for 0, 45, and 59 fail. Each test earns its place. None of my 11 injected bugs survived this suite.
If you wrote tests that cover both sides of the one-hour boundary and the error case before looking at any code, you practiced the main skill of this article.
You can repeat Exercise 1’s method on any function you own. Break one line on purpose, run the tests, and add a test whenever they stay green.
11. Common Mistakes
- Writing the test after reading the code: You will test what it does, not what it should do.
- Only testing the happy path: Weak suites in my experiment caught 64% of injected bugs.
- Computing expected values with the code: The test then agrees with the code by construction.
- Asking the AI to “write tests for this code”: In my test, that caught the bug in 6 of 15 suites and locked it in in 8.
- Trusting “all tests passed”: Models were shown tests and still failed some, so run them yourself.
- Treating coverage as the goal: A suite can cover every line and still miss most bugs.
- Skipping the red step: A test that has never failed might never fail.
- Deleting a failing test to make the suite green: The test was telling you something.
12. Frequently Asked Questions
Do I need pytest?
No, unittest ships with Python and was enough for everything here. Many developers prefer pytest for shorter tests and clearer failure output. I used unittest and plain asserts, and I did not test pytest.
How many tests are enough?
There is no number. Ask whether your tests cover the boundaries, the empty case, and every error. Then break the code on purpose. When a deliberate bug leaves the tests green, you need another test.
Should the AI write my tests?
It can help, if you give it the description and review the result. In Experiment 3, spec-based tests were sound and caught the bug in 14 of 15 suites. Review them as you would review code, because they still missed the bug once.
Is 100% coverage a good goal?
It is a useful warning light. Low coverage shows code that no test touches. High coverage does not show that the tests check anything, as the published research and my weak suites both show.
Does test-first development always apply?
It works best when you can describe the behavior before the code exists, which is true for functions like these. For exploratory work, such as a user interface you are still designing, it is harder. Add the tests as soon as the behavior settles.
What about AI agents that run the tests themselves?
I did not test agents in this article, but Part 6 does. The same habits apply. Read any change an agent makes to the tests, because a test that was edited to pass protects nothing. In Part 6, no agent edited a test file, in 44 runs with one. A small local agent changed the code to match a wrong test in 9 of 15 runs and never told me, while Sonnet 5.5 and Opus 5.5 reported the conflict every time.
13. Conclusion
Tests are the safety net under AI-written code. They state your intent, they catch the almost-right answer, and they let you simplify and change code without fear. The skill is writing tests that can fail, and then proving that they can.
My experiments showed three things. Weak suites that ran 87% of the lines caught only 64% of injected bugs, while strong suites caught 93%. Strong tests cut the model’s failures on the behaviors they state from 18% to 4%, although it still failed some tests it was shown. And tests written from the buggy code caught the bug in 6 of 15 suites, against 14 of 15 when the model saw the description.
So write the behavior down before the code, test the boundaries and the errors, run the tests yourself, and break your code on purpose. The final article in this series puts everything together: building something small with an agent, and owning every part of it. Tools and guidance change, so treat the specifics here as accurate as of early December 2026.
14. References
Research
- Inozemtseva and Holmes: Coverage is not strongly correlated with test suite effectiveness (ICSE 2014)
- Mathews and Nagappan: Test-Driven Development for Code Generation (arXiv)
- Petrovic and Ivankovic: State of Mutation Testing at Google (ICSE-SEIP 2018)
- Stack Overflow: the 2025 Developer Survey results
Tools and documentation
- Python:
unittest, the unit testing framework - Python: the
assertstatement - Python: the
astmodule, used to inject bugs - pytest documentation
- mutmut: a mutation testing tool for Python
On this site
- Part 1: What still matters
- Part 2: Using AI as a tutor, not a ghostwriter
- Part 3: Reading and reviewing AI-generated code
- Part 4: Debugging without handing everything to the AI