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
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
- 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
Example: discount helper + pytest
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.
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 passedHow to get useful tests
- Prefer tests that would fail if the code were wrong — not tests that only assert True.
- Name tests after behaviour (test_flat50_floor), not test1.
- Ask for table-driven tests in Go, or parametrize in pytest, when you have many similar cases.
- For legacy code: ask for characterisation tests that lock today’s outputs before you refactor.
- Run the suite in your IDE or CI — do not trust a chat that says “all passed” without a log.
| Pattern | Tip |
|---|---|
| Tests first (TDD-ish) | Ask for failing tests, then for code that passes them. |
| Code first | Paste the function; ask for tests that cover edges. |
| Bug fix | Write a failing test that reproduces the bug, then fix. |
| AI agent | Allow it to run the test command; keep approval on. |
Settings tip
- Put the exact test command in project rules (pytest -q, npm test, mvn test).
- In Copilot / Claude Code / Cursor Agent: “add tests and run them; stop if red.”
- 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.
नमस्कार मित्रांनो. इथे code आधीच बरोबर चालतो, आणि AI कडून चांगल्या tests लिहून घेणं हे आपलं काम आहे. Tests pass झाल्यावर आपण एक मिनिट मुद्दाम code बिघडवू, आणि tests ती चूक खरंच पकडतात का ते बघू. इथली जत्रा आणि किंमती फक्त practice साठी आहेत.
नमस्कार दोस्तों. यहाँ code पहले से सही चलता है, और AI से अच्छे tests लिखवाना हमारा काम है. Tests pass होने के बाद हम एक मिनट के लिए जानबूझकर code बिगाड़ेंगे, और देखेंगे कि tests वह गलती सच में पकड़ते हैं या नहीं. यहाँ का मेला और कीमतें सिर्फ practice के लिए हैं.
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.
Ravindra Bagale's Tip – मराठी
AI कडे नेहमी boundary values मागा, जसं 4 आणि 5 किंवा 17 आणि 18. बहुतेक खरे bugs एक rule संपतो आणि दुसरा सुरू होतो तिथेच लपलेले असतात.
Ravindra Bagale's Tip – हिंदी
AI से हमेशा boundary values माँगो, जैसे 4 और 5 या 17 और 18. ज़्यादातर असली bugs वहीं छिपे होते हैं जहाँ एक rule खत्म होता है और दूसरा शुरू होता है.
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
"""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):
promptWrite 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.
- Create a project folder and open a terminal inside it.
- Create a virtual environment: on macOS or Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv. - 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. - Save the code above as
ticket.py. - Send the prompt to your AI assistant and paste your real
ticket.pywhere the prompt says so. - 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.
- Save the tests as
test_ticket.pyin the same folder. You can compare with the optional solution below. - Run the tests with
python -m unittest -v test_ticket.pyand confirm that the last line saysOK. - Test the tests: in
ticket.py, changeelif age < 18:toelif age <= 18:, save, and runpython -m unittest test_ticket.py. A good test file must now report a failure for age 18. - Undo the change so the line says
elif age < 18:again, save, and run the tests once more to seeOK.
Real output with correct code (the time in seconds can be slightly different on your computer):
terminalpython -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):
terminalpython -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.
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
- Output:
Ran 0 testsandNO TESTS RAN. Fix: every test method name must start withtest_, and the class must inherit fromunittest.TestCase. - Error:
ModuleNotFoundError: No module named 'ticket'. Fix: run the command from the folder that containsticket.py, and check the exact file name. - Error:
ImportError: cannot import name 'ticket_prices' from 'ticket'. Fix: the AI misspelled the function name, so change the import toticket_price. - 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.
- 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.
Check the AI's expected values
Break the code to test your tests
AI चे expected answers तपासा
Tests ची पण परीक्षा घ्या
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
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.