AI Test Generation
Use AI to generate test cases, test code, and test data, and apply checks that separate meaningful tests from tests that merely look thorough.
Introduction
Ask an assistant to “write tests for this file” and you will get a lot of tests, quickly. Most will pass. Many will be nearly worthless.
The core problem is that a model given only the implementation will write tests that describe what the code does, including its bugs. Tests derived this way can never disagree with the code. Good generation starts from requirements and risk, and ends with a deliberate check that the tests can actually fail.
Learning Objectives
- Explain the main failure modes of AI-generated tests.
- Choose inputs (requirements, specifications, examples) that produce meaningful tests.
- Write prompts that generate tests, data, and mocks safely.
- Apply a quality checklist to generated tests.
- Use mutation-style checks and manual fault injection to prove that tests detect defects.
- Integrate generated tests into the codebase responsibly.
1. How Generated Tests Go Wrong
| Failure mode | What it looks like |
|---|---|
| Mirror tests | The test repeats the implementation’s logic, so it passes by construction |
| Assertion-free or weak assertions | assert result is not None; the test executes code but verifies little |
| Over-mocking | Everything is mocked, so the test checks the mocks, not behavior |
| Happy-path bias | Several variations of the normal case; no boundaries or failures |
| Wrong expected values | The model guessed the correct output and guessed wrong |
| Brittle tests | Coupled to implementation details; break on harmless refactoring |
| Duplicates | Many tests of the same partition, inflating counts |
| Invented behavior | Tests for features the code does not have, or APIs that do not exist |
| Tautological fixtures | Test data created by the same function being tested |
All of these inflate your test count and coverage while contributing little protection.
2. Generate From the Right Sources
Prefer inputs in this order:
- Requirements and acceptance criteria (what should happen).
- Technique-derived cases from lesson 2 (partitions, boundaries, decision tables).
- Examples from real usage, bug reports, and customer files (anonymized).
- The interface (signatures, types, contracts).
- The implementation, last, and mainly to understand structure and dependencies.
When the implementation is the only source, treat the output as characterization tests (lesson 9 of the previous course): they record behavior and help refactoring, but they do not verify correctness.
3. A Two-Step Prompt: Cases First, Code Second
Separate deciding what to test from writing the code. Review the cases before any code exists.
Step 1: Test cases
1
2
3
4
5
6
7
8
9
10
11
Act as a test analyst. Using the requirement and rules below,
propose test cases. Do not look at the implementation.
Requirement: [paste with acceptance criteria]
Rules and limits: [paste]
Output a table: ID, purpose, input, expected result, technique used
(partition, boundary, decision table, state, error guess).
Include invalid inputs, boundaries, and failure paths, not only
the happy path.
Mark every expected result you are not certain about as "NEEDS DECISION".
You review, correct the expected values, and remove duplicates.
Step 2: Test code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Write pytest tests for the approved cases below.
Context:
- Function under test: [signature and module]
- Existing test style to follow: [paste an example test]
- Fixtures available: [list]
Rules:
- One behavior per test; descriptive test names.
- Assert specific outcomes (values, error codes), not just "no error".
- Do not mock the unit under test or the database in integration tests.
- No logic (loops, conditionals) in assertions; use parametrization
for table-driven cases.
- Do not modify production code.
Approved cases: [paste table]
4. Generating Test Data
Assistants are useful for creating realistic, varied synthetic data: awkward CSV files, multilingual text, long strings, malformed rows, and boundary dates.
1
2
3
4
5
6
7
Generate 20 synthetic customer feedback rows for CSV import testing.
Columns: body, source, date.
Include: plain English, non-English text, emoji, text with commas and
quotes, multi-line text, very short and very long entries, leading and
trailing whitespace, dates in valid and invalid formats, duplicates.
Label each row with the case it represents. Use no real names, emails,
or company information.
Check generated data for realism and for anything that looks like real personal data. Keep data files in the repository with a note about what each one tests.
5. Quality Checklist for a Generated Test
Before accepting a test, ask:
- What requirement or risk does it cover? If you cannot name it, delete it.
- Is the expected value derived independently of the implementation?
- Would it fail if the behavior broke? (See section 6.)
- Does it assert something specific, and the right thing?
- Is it independent: no reliance on order or shared state?
- Is it deterministic: no real time, randomness, or network without control?
- Is it readable: a failure message tells someone what went wrong?
- Is it at the right level and not duplicating a cheaper test?
- Does it test behavior, not private implementation details?
6. Prove That Tests Can Fail
A test you have never seen fail is a test you cannot trust.
Manual fault injection. Introduce a plausible bug in the code and run the tests:
- Change
<=to<in a limit check. - Remove the tenant filter from a query.
- Swallow an exception.
- Skip the duplicate check.
If the suite stays green, you have found a gap. Revert the bug and strengthen the test.
Mutation testing. Tools automate this: they apply many small code changes (mutants) and report which ones no test detected (survivors). Survivors point to missing or weak assertions. Lesson 9 covers this further. A practical approach: ask the assistant to suggest the mutants most likely to survive in a given function, then try them yourself.
1
2
3
4
Here is a function and its tests. List ten small, plausible defects
(mutations) that a developer could realistically introduce, and say
which of the existing tests, if any, would catch each one. Identify
the mutations that no test would catch, and suggest tests for them.
Verify the claims by actually applying the mutations.
7. Governance of Generated Tests
- Review like production code. A generated test is code with a maintenance cost.
- Keep what you can explain. Delete tests that do not cover a requirement or risk.
- Mark provenance if your team’s policy requires it, and keep prompts for important cases in the repository.
- Do not let the assistant edit tests to make them pass without your explicit review of why. A common failure is an assistant “fixing” a failing test by changing the assertion to match buggy output.
- Watch for overfitting to the prompt’s examples: tests that only cover the examples you supplied.
- Never use real data in prompts or fixtures.
8. Practical Exercise
For SignalDesk (or your project):
- Pick a function or flow with accepted requirements, such as row validation or listing with tenant scope.
- Run the “implementation only” baseline: give the assistant the code and ask for tests. Record how many tests, what they assert, and which checklist items they fail.
- Run the two-step method: generate cases from requirements, correct the expected values, then generate code.
- Compare the two suites using the checklist, and by running manual fault injection with at least five mutations. Record which suite caught more.
- Generate a synthetic data file and use it in a test.
- Delete or fix every generated test that fails the checklist, and record why.
Verification
You are ready to continue when:
- Every kept test traces to a requirement or risk.
- Expected values were set from requirements, not from the implementation.
- Fault injection shows the suite catches the planted defects, and gaps are fixed.
- No test was modified to pass without understanding why it failed.
- Synthetic data contains no real personal data.
Key Takeaways
- Tests generated from code alone mirror the code, bugs included.
- Decide cases first from requirements, then generate code from approved cases.
- A test you have never seen fail is not yet evidence.
- Use fault injection and mutation testing to measure test strength.
- Generated tests carry maintenance costs; review them like production code.
What’s Next?
With a method for generating and checking tests, we can write them at each level. Next, we start at the base of the pyramid with unit tests.