Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 5 · WORKFLOWS

How to Write Tests with AI

Ask the AI for tests the same way you ask for code: clear inputs, expected outputs, and edge cases. Then run the suite yourself. Green tests are the proof.

In short: describe behaviour → ask for tests first or right after the function → run pytest / node --test / JUnit → keep only tests you understand.

Why AI-written tests help

WHY

Writing every edge case by hand is slow. AI is good at listing empty, zero, negative and “unknown input” cases. Bad AI tests just copy the bug. You must read assertions and run them.

What a good test prompt has

WHAT
  • Behaviour: what “correct” means in one sentence.
  • Framework: pytest, node --test, JUnit 5, xUnit, cargo test…
  • Cases: happy path + at least two edges + one error path.
  • Rules: “no network”, “no real clock”, “use temp dirs” when needed.

How writing tests flows

1 · State behaviour + framework 2 · AI writes tests you read them 3 · Run the suite watch failures 4 · Fix code or tests smallest change 5 · Keep meaningful asserts delete noise

Example: discount helper + pytest

TEST PROMPT (COPY)

Here is final_price. Write pytest tests: no coupon, SAVE10, FLAT50 when price < 50 (floor at 0), unknown coupon raises ValueError. No extra files beyond test_discount.py.

discount.py
def final_price(price: float, coupon: str | None = None) -> float:
    if price < 0:
        raise ValueError("price must be >= 0")
    if coupon is None:
        return round(price, 2)
    if coupon == "SAVE10":
        return round(price * 0.9, 2)
    if coupon == "FLAT50":
        return round(max(price - 50, 0), 2)
    raise ValueError(f"unknown coupon: {coupon}")
test_discount.py (tested here)
import pytest
from discount import final_price

def test_no_coupon():
    assert final_price(200) == 200.0

def test_save10():
    assert final_price(200, "SAVE10") == 180.0

def test_flat50_floor():
    assert final_price(30, "FLAT50") == 0.0

def test_unknown():
    with pytest.raises(ValueError):
        final_price(100, "BOGUS")
cd code/tests
python3 -m pytest -q
# -> 4 passed

How to get useful tests

HOW
  1. Prefer tests that would fail if the code were wrong — not tests that only assert True.
  2. Name tests after behaviour (test_flat50_floor), not test1.
  3. Ask for table-driven tests in Go, or parametrize in pytest, when you have many similar cases.
  4. For legacy code: ask for characterisation tests that lock today’s outputs before you refactor.
  5. Run the suite in your IDE or CI — do not trust a chat that says “all passed” without a log.
PatternTip
Tests first (TDD-ish)Ask for failing tests, then for code that passes them.
Code firstPaste the function; ask for tests that cover edges.
Bug fixWrite a failing test that reproduces the bug, then fix.
AI agentAllow it to run the test command; keep approval on.
Rule: delete tests that only mirror the implementation line-by-line with no real assertion. They give fake confidence.

Settings tip

  1. Put the exact test command in project rules (pytest -q, npm test, mvn test).
  2. In Copilot / Claude Code / Cursor Agent: “add tests and run them; stop if red.”
  3. Keep fixtures small. Do not paste production databases into the chat.

Try this yourself: ask AI to write tests, then test the tests

Hello friends. Here the code already works, and our job is to get good tests from the AI. After the tests pass, we will break the code on purpose for one minute to check that the tests really catch the mistake. The fair and the prices are fictional practice data.

Ravindra Bagale's Tip

Always ask the AI for boundary values such as 4 and 5 or 17 and 18. Most real bugs hide exactly where one rule ends and the next rule starts.

Environment (tested): this exercise was run on 6 November 2026 with Python 3.13.5. It uses the built-in unittest module, so you do not need to install anything. The optional pytest step was checked with pytest 9.2.0. Use Python 3.10 or newer.

Your task: a pretend science fair sells tickets with these rules. Children under 5 are free, ages 5 to 17 pay 100 rupees, ages 60 and above pay 120 rupees, and everyone else pays 200 rupees. Members get 10 percent off, and a negative age is an error. The function below already follows these rules, but it has no tests. Ask an AI assistant to write unittest tests, run them, and then check that the tests can catch a real mistake.

Code to test — save this exact text as ticket.py

ticket.py
"""Fictional practice: ticket price rules for a pretend science fair."""


def ticket_price(age: int, is_member: bool = False) -> int:
    """Return the ticket price in rupees for the pretend fair.

    Children under 5 are free, ages 5 to 17 pay 100, ages 60 and above
    pay 120, and everyone else pays 200. Members get 10 percent off.
    A negative age raises ValueError.
    """
    if age < 0:
        raise ValueError("age cannot be negative")
    if age < 5:
        price = 0
    elif age < 18:
        price = 100
    elif age >= 60:
        price = 120
    else:
        price = 200
    if is_member:
        price = price * 90 // 100
    return price

Prompt to give your AI assistant (Copilot Chat, ChatGPT, Claude, Gemini or any similar tool):

prompt
Write unittest tests for this Python function. Use only the Python standard library.

(paste the whole ticket.py file here)

Cover these cases:
1. Every age boundary: 0, 4, 5, 17, 18, 59 and 60. Use self.subTest for this table.
2. The 10 percent member discount for an adult, a child and a senior.
3. A free child who is also a member must still pay 0.
4. A negative age must raise ValueError.

Read the docstring for the rules. Do not change ticket.py.
After the code, explain in one short sentence what each test protects.
HOW
  1. Create a project folder and open a terminal inside it.
  2. Create a virtual environment: on macOS or Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv.
  3. Activate it: on macOS or Linux run source .venv/bin/activate. In Windows Command Prompt run .venv\Scripts\activate.bat, and in Windows PowerShell run .venv\Scripts\Activate.ps1.
  4. Save the code above as ticket.py.
  5. Send the prompt to your AI assistant and paste your real ticket.py where the prompt says so.
  6. Check every expected number in the AI tests against the rules in the docstring before you run anything. If the AI expects 100 for age 18, the test is wrong, so fix the test and not the code.
  7. Save the tests as test_ticket.py in the same folder. You can compare with the optional solution below.
  8. Run the tests with python -m unittest -v test_ticket.py and confirm that the last line says OK.
  9. Test the tests: in ticket.py, change elif age < 18: to elif age <= 18:, save, and run python -m unittest test_ticket.py. A good test file must now report a failure for age 18.
  10. Undo the change so the line says elif age < 18: again, save, and run the tests once more to see OK.

Real output with correct code (the time in seconds can be slightly different on your computer):

terminal
python -m unittest -v test_ticket.py
test_age_boundaries (test_ticket.TicketPriceTests.test_age_boundaries) ... ok
test_free_child_stays_free_for_members (test_ticket.TicketPriceTests.test_free_child_stays_free_for_members) ... ok
test_member_discount (test_ticket.TicketPriceTests.test_member_discount) ... ok
test_negative_age_raises (test_ticket.TicketPriceTests.test_negative_age_raises) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

Real output after the deliberate mistake (the age 18 subtest catches it):

terminal
python -m unittest test_ticket.py
F...
======================================================================
FAIL: test_age_boundaries (test_ticket.TicketPriceTests.test_age_boundaries) (age=18)
----------------------------------------------------------------------
Traceback (most recent call last):
  ...
AssertionError: 100 != 200

----------------------------------------------------------------------
Ran 4 tests in 0.000s

FAILED (failures=1)

Optional: pytest can also run unittest tests. After python -m pip install pytest, pytest 9.2.0 printed this. pytest 9 counts each subTest separately, while older pytest versions show only 4 passed.

terminal
python -m pytest -q test_ticket.py
....                                                              [100%]
4 passed, 7 subtests passed in 0.00s
Optional solution for test_ticket.py (try it yourself first)

Your AI assistant may write the tests differently. That is fine if every expected number matches the rules and the deliberate mistake makes at least one test fail.

test_ticket.py
"""unittest tests for the fictional ticket_price practice."""
import unittest

from ticket import ticket_price


class TicketPriceTests(unittest.TestCase):
    def test_age_boundaries(self):
        cases = [(0, 0), (4, 0), (5, 100), (17, 100), (18, 200), (59, 200), (60, 120)]
        for age, expected in cases:
            with self.subTest(age=age):
                self.assertEqual(ticket_price(age), expected)

    def test_member_discount(self):
        self.assertEqual(ticket_price(30, is_member=True), 180)
        self.assertEqual(ticket_price(10, is_member=True), 90)
        self.assertEqual(ticket_price(65, is_member=True), 108)

    def test_free_child_stays_free_for_members(self):
        self.assertEqual(ticket_price(3, is_member=True), 0)

    def test_negative_age_raises(self):
        with self.assertRaises(ValueError):
            ticket_price(-1)


if __name__ == "__main__":
    unittest.main()

Troubleshooting this exercise

HOW
  1. Output: Ran 0 tests and NO TESTS RAN. Fix: every test method name must start with test_, and the class must inherit from unittest.TestCase.
  2. Error: ModuleNotFoundError: No module named 'ticket'. Fix: run the command from the folder that contains ticket.py, and check the exact file name.
  3. Error: ImportError: cannot import name 'ticket_prices' from 'ticket'. Fix: the AI misspelled the function name, so change the import to ticket_price.
  4. Problem: a test fails because the AI expected the wrong price. Fix: compare the number with the docstring rules. Change the wrong test, not the working code.
  5. Problem: the deliberate mistake did not make any test fail. Fix: check that you saved the edited file. If it still passes, ask the AI to add a test for age 18 and age 17.

Practice cards: English and spoken Marathi

Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.

PRACTICE CARDAI Coding

Check the AI's expected values

An AI can write a test that expects the wrong answer, so read every expected number before you trust the test.
When a test and the written rules disagree, fix the test and leave the working code alone.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Break the code to test your tests

Change one small rule in the code on purpose and run the tests again.
If no test fails, your tests are too weak, so ask the AI to add the missing boundary case and then undo your change.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

AI चे expected answers तपासा

AI चुकीचं उत्तर expect करणारी test पण लिहू शकतो, म्हणून test वर विश्वास ठेवण्याआधी प्रत्येक expected number वाचा.
Test आणि लिहिलेले rules जुळत नसतील, तर test दुरुस्त करा आणि चालणारा code तसाच ठेवा.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Tests ची पण परीक्षा घ्या

Code मधला एक छोटा rule मुद्दाम बदला आणि tests पुन्हा चालवा.
एकही test fail झाली नाही तर tests कमजोर आहेत, म्हणून AI कडून missing boundary case ची test लिहून घ्या आणि मग बदल परत करा.
Ravindra Bagale · ravindrabagale.com/ai-coding
Practice label: every name, number and time in this exercise is fictional teaching data. It is not about a real person, account or company. Passing these tests proves only the cases listed in the tests, not every possible input.

Quick quiz

1. What must you do after the AI writes tests?

Read the asserts and run the suite yourself.

2. What is a characterisation test?

A test that locks current behaviour before a refactor.

3. Name one edge case to always request

Empty/zero/negative input, or an unknown/invalid value.

4. Why avoid “assert True”?

It never catches a real bug.

Save tokens and money

SMART AI USE

Ask for the test file once with a clear case list. Do not regenerate the whole suite after every tiny code tweak — update the one failing case.

Save these cards

INTERVIEW CARDAI Coding

How do you write tests with AI?

State behaviour + framework + edge cases.
Run the suite; keep only meaningful asserts.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

Tests first vs code first

Tests first: locks the goal early.
Code first: faster for tiny helpers — still add edges.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Tests in 3

Describe behaviour.
Generate + read tests.
Run the real suite.
Ravindra Bagale · ravindrabagale.com/ai-coding