Writing Tests with AI Help
AI assistants can generate test cases quickly, but the developer must verify that the tests cover the right behaviour and are not trivially true.
Writing tests is tedious. AI assistants can generate test cases quickly, but the quality varies and the developer is responsible for what goes into the codebase.
What to ask the AI for
Paste in the function and ask for unit tests. Specify the testing library if you have one. Explicitly ask for edge cases: null inputs, empty arrays, negative numbers, strings where numbers are expected. The assistant will generate a reasonable set of cases, but it will usually miss the edge cases specific to your business logic unless you describe them.
Reading AI-generated tests critically
A test is only useful if it fails when the function is broken. Some AI-generated tests are trivially true: they test that the function returns something, not that it returns the right thing. Read each assertion and ask: would this test catch a bug in the logic?
Also check: does the test set up its input correctly? Does the expected output match what the function should actually return? Are there any cases your users hit regularly that are not covered?
A concrete example
A developer has a function that formats a price as a currency string. They paste it in and ask for unit tests. The assistant produces tests for a standard positive number, zero, and a large number. The developer adds two more by hand: a negative number (refund), and a number with more than two decimal places (floating point). Those are the cases that matter for the business.
code: | function formatPrice(amount) { if (typeof amount !== "number") return "N/A"; return "$" + amount.toFixed(2); } // Simple inline checks (not a real test framework) console.log(formatPrice(9.99)); console.log(formatPrice(0)); console.log(formatPrice(-5)); console.log(formatPrice("abc")); codeOutput: "$9.99\n$0.00\n$-5.00\nN/A" canRun: true
Try it
Take a function you wrote recently and ask the AI to generate unit tests for it. Read each test and check whether it would actually fail if the function had a bug. Add or remove tests based on your review.
Quick check
What is the main risk of AI-generated tests?
Quick check
What context helps AI generate better tests?
Quick check
Who is responsible for the quality of tests in a codebase?

