AI Prompts for Writing Unit Tests: A Practical Guide

Programmer working at a laptop, writing unit tests with AI assistance

AI writes reliable unit tests when you separate planning from generation: first ask it to list edge cases in plain language, then ask a coding-focused prompt to turn that list into actual test code against your real file and framework. Skipping straight to “write unit tests for this function” usually produces tests that pass but don’t actually cover the cases that break in production. Here’s a two-step approach that fixes that.

Why Does “Write Unit Tests for This” Produce Weak Coverage?

A bare request to generate tests tends to produce tests for the obvious happy path — normal inputs, expected outputs — because that’s the pattern most represented in typical code. It’s much less likely to surface the inputs that actually cause bugs: empty strings, null values, negative numbers, boundary values, race conditions, or malformed data. The fix isn’t a better one-line prompt; it’s splitting the task into a reasoning step and a code-generation step.

How Do You Prompt for Edge Cases Before Writing Any Code?

Start with a plain-language prompt that asks the model to reason about the function’s behavior, not generate code yet: “list the critical edge cases for this function, grouped by input validation, boundary conditions, and error handling — don’t write test code yet, just list the cases and why each one matters.” This step surfaces the assumptions the code makes that aren’t obvious from reading it once, and it gives you something to review and correct before any test code gets written. If the model’s list misses something you know matters for your domain, add it manually before moving to the next step.

How Should You Prompt for the Actual Test Code?

Once you have a solid edge-case list, the second prompt should be specific about your stack: name the testing framework, the file being tested, and any coverage target. A prompt like “write Jest unit tests for this file covering the edge cases listed above, aiming for at least 80% branch coverage, and follow the existing test file’s naming conventions” gives the model enough constraint to produce tests that fit your codebase instead of a generic example. Referencing your actual framework and file matters — a generic “write unit tests” prompt is far more likely to use a different assertion style or mocking pattern than what the rest of your codebase already uses.

How Do You Prompt for Tests on Legacy Code Safely?

For legacy code you don’t want to risk changing, explicitly instruct the model not to modify the logic under test: “add unit tests for this file without changing any of the existing logic, even if you notice something that looks like a bug — flag it separately instead.” This separation matters because a model asked to “fix and test” legacy code at the same time can quietly change behavior while writing what look like passing tests, which defeats the purpose of adding a safety net before a refactor. Our guide to AI code review prompts covers how to prompt for spotting those bugs separately, once they’re flagged rather than silently fixed.

What Should You Ask For Beyond Basic Example-Based Tests?

For functions with complex or numeric logic, ask explicitly for property-based or fuzz-style tests in addition to example-based ones — tests that check a general property holds across a wide range of generated inputs, rather than just a handful of hand-picked examples. This is also where it helps to ask the model to validate business logic against a written spec first, if one exists, since a test suite is only as good as its understanding of what the code is actually supposed to do. When mocking external services, specify exactly which service or library to mock and give a concrete example of the expected interaction, rather than leaving the mocking strategy up to the model’s guess. For a related technique on isolating and fixing failures once tests catch something, see our guide to AI prompts for debugging Python code.

Frequently Asked Questions

Can AI-generated unit tests fully replace manual test writing?

Not entirely. AI is strong at generating boilerplate and covering edge cases you name or that it identifies from common patterns, but a human still needs to confirm the tests check the right behavior, not just that they pass. Treat AI-generated tests as a fast first draft that gets reviewed, not a finished, unreviewed test suite.

Should I ask for high coverage percentage or good edge-case coverage?

Prioritize edge-case coverage. A high coverage percentage can be achieved by writing shallow tests that execute a line of code without actually verifying its behavior is correct, so a coverage number alone doesn’t guarantee the tests are catching real bugs. Use a coverage target as a rough guide, not the primary goal of the prompt.

Why do AI-generated tests sometimes fail to compile or run?

Usually because the model wasn’t given enough context about your actual file structure, imports, or testing framework version. Pasting in the real file, an existing test file as a style example, and your framework’s version number substantially reduces this kind of error compared to a prompt with no surrounding context.

Anthropic’s own writeup on writing reliable unit tests with Claude covers this two-phase brainstorm-then-generate workflow in more detail if you want to see it applied end to end.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Rolar para cima