AI Agents and Coding Assistants

Using AI to Write Tests Without Fooling Yourself

AI can draft tests quickly, but tests copied from the code prove little. Learn where expected answers should come from.

Key takeaways

  • Expected results should come from requirements, worked examples or a trusted reference, not from the code under test.
  • A passing run means little until you have seen the relevant tests fail for a realistic fault.
  • Watch for weak assertions, heavy use of fake components and edits that loosen tests to make them pass.
  • Use the assistant to brainstorm cases and write routine setup, while a person owns the meaning of each expectation.

AI can write tests quickly, and many of them will pass on the first run. That is only reassuring if the expected answers came from somewhere other than the code being tested. Decide what correct behavior is, let the assistant help turn those decisions into tests and then confirm that the tests fail when the code is wrong.

A test is a small program that runs your code with chosen inputs and compares the result with what should happen. The comparison is its whole value. If "should happen" is simply "whatever happens now," the test records behavior without judging it.

How a green result can mislead

Suppose the rule for a shop is that shipping is free for orders of 50 or more and otherwise costs 6. A generated function reads like this.

def shipping(total):
    if total > 50:
        return 0
    return 6

Now you ask an assistant to write tests for this code. It reads the function and produces expectations that match: an order of 30 costs 6, an order of 80 costs 0 and an order of 50 costs 6. All three pass. The third is wrong, because the rule says an order of exactly 50 ships free.

The fault is a single character, > where >= was needed. The test did not catch it; it certified it. Had you given the assistant the rule and asked for tests before showing it any code, the boundary case would have had the right expectation and failed.

def test_exactly_fifty_ships_free():
    assert shipping(50) == 0

Ask where the expected answer comes from

Testers call the source of truth an oracle. For every expectation, you should be able to name it.

Source of the expected answer How much it tells you
A written requirement or agreed rule Strong, if the rule is right
An example worked by hand Strong for that case
A trusted older system or published standard Good, with care about differences
A general property that must always hold Good across many inputs
The current output of the code Only that behavior has not changed

The last row has a legitimate use. Before reorganizing old code that nobody fully understands, tests that capture present behavior help you notice changes. Name them honestly as snapshots, and do not read them as proof of correctness.

A workflow that keeps you honest

Order matters. Settle the expectations before the code can influence them.

Writing tests so the code cannot grade itself
1 State rules Write behavior and edge cases in plain words 2 Draft cases Ask for tests from the rules, not the code 3 Check answers Verify each expected value yourself 4 See failure Run against missing or broken code 5 Implement Write or fix code without loosening tests 6 Probe again Plant a fault and confirm it is caught State rules Write behavior and edge cases in plain words 1 Draft cases Ask for tests from the rules, not the code 2 Check answers Verify each expected value yourself 3 See failure Run against missing or broken code 4 Implement Write or fix code without loosening tests 5 Probe again Plant a fault and confirm it is caught 6

If code already exists, you can still do most of this. Start a fresh session, give the assistant the requirement and the function's name and inputs, and leave out the body. Compare what it expects with what the code does, and investigate every disagreement. Either side may be wrong.

Use the assistant for breadth

Where assistants often shine is in suggesting cases you had not considered. Try requests such as "list inputs that could break this rule" or "which situations does my description leave undefined?"

Useful families of cases include these.

  • Boundaries: just below, exactly at and just above a limit.
  • Empty things: no items, blank text, missing fields.
  • Extremes: very large numbers, very long input.
  • Invalid input: negative totals, wrong types, impossible dates.
  • Format variety: accents, other alphabets, different date styles, time zones.
  • Repetition and timing: the same request sent twice, two users at once.
  • Failures: a service that times out or returns nonsense.

The second request is especially valuable. What should shipping cost for a negative total? The rule did not say. That is a question for a person who owns the policy, and a tool should not settle it silently.

A worked session

Suppose you need a function that decides whether a user may cancel a booking. Start with the rules in your own words: the owner may cancel up to 24 hours before the start, staff may cancel at any time and nobody may cancel a booking that is already cancelled.

Ask the assistant to turn these into a table of cases before writing code. A good table might list an owner cancelling 25 hours ahead (allowed), an owner at 23 hours (refused), staff one hour ahead (allowed), a stranger a week ahead (refused) and staff cancelling a cancelled booking (refused).

Reading the table, you notice a hole. What about an owner at exactly 24 hours? Your phrase "up to 24 hours before" suggests it is allowed, so you say so and add the row. Another: what happens after the booking has started? You decide staff may still cancel, to handle no-shows, and record that decision.

Only now do you ask for test code and then the function. The tests should pass the current time into the function instead of reading the computer's clock, so that "exactly 24 hours" means the same thing on every run. If the assistant's first function reads the clock directly, ask it to change that design.

Finally, check the setup of each test. A test for "stranger is refused" that accidentally creates a cancelled booking will pass for the wrong reason. Each refusal case should differ from an allowed case in just the one fact being tested.

Spot tests that prove little

Read generated tests as critically as generated code. Common weaknesses are easy to recognize once named.

  • Weak assertions. Checking only that a result exists, or that nothing crashed.
  • Mirrored logic. The test repeats the same calculation as the code, so both share any mistake.
  • Too many stand-ins. A mock is a fake replacement for a real component. If everything is mocked, the test may only confirm that the fakes were called.
  • Hidden skips. Tests marked to be ignored, or errors caught and discarded.
  • Fragile detail. Tests that break on harmless changes train people to update expectations without reading them.
  • Flakiness. Results that change between runs, often because of time, randomness or network access.

When an assistant is asked to fix failing tests, check which side it changed. Editing the expectation, widening an allowed range or special-casing the test's exact input are all ways to turn the screen green without fixing anything. State plainly that tests may not be altered without your approval, and review the changes anyway, as part of a code review checklist.

Check that your tests can catch faults

Coverage tools report which lines ran during testing. That helps you find untested areas, but a line can run without its result being checked. High coverage is compatible with poor tests.

A sharper check is to break the code on purpose. Change >= to >, remove a permission check or return an empty list, then run the tests. If everything still passes, you have found a gap. Doing this automatically is called mutation testing, and tools exist for many languages. Restore the code afterward.

Another approach is property-based testing, where you state something that must always be true and a tool generates many inputs. For shipping, the cost for a valid order should always be 0 or 6, and a larger order should never cost more to ship than a smaller one. Properties catch surprises but will not replace specific examples: a function that always returns 6 satisfies both.

Several levels of testing

Unit tests check small pieces in isolation. Integration tests check that pieces work together, for instance your code with a real test database. End-to-end tests follow a user's path through the whole system. Assistants can help with all three, though the larger ones need an environment you control.

Never point generated tests at live data or real payment, email or messaging services. Use test accounts and invented records, as described in sandboxes and test accounts. Tests also miss things they never ask about, so security review and watching real use remain necessary; see common security mistakes.

The same thinking applies when the product itself contains a model and answers vary. There you judge samples against criteria, an idea introduced in testing an AI tool before relying on it.

Common questions

Should I let the AI write both the code and the tests?

You can, if a person supplies or verifies the expectations. When one source writes both from the same misunderstanding, they will agree with each other and still be wrong.

How many tests are enough?

Enough that the failures you most fear would be noticed. Concentrate on rules involving money, access, data loss and safety, and on places that have broken before.

What if I cannot read test code?

Ask for a table of cases with inputs and expected results in plain words, check that table yourself and try several cases by hand in the running program. For anything with serious consequences, have someone who reads code confirm that the tests match the table.

Written for 4ArtificialIntelligence with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 46 articles in AI Agents and Coding Assistants →

Latest news on this topic