AI Business16 min read

Unit Tests With AI: Generate, Check and Trust Them

Use AI to draft unit tests and find test cases you would miss, then verify them. A step-by-step workflow with prompts, review checks and the evidence behind them.

Unit Tests With AI: Generate, Check and Trust Them

Unit Tests With AI: Generate, Check and Trust Them

Developer checking an AI-generated unit test suite

AI can draft a unit test suite in minutes and surface test cases you would have forgotten. What it cannot do is know what your code is supposed to do. The workflow that works has two halves: let the AI write the first draft fast, then prove that every test can actually fail. In our AmmarAI workspace, the AI code generator handles functions, tests and queries, so drafting and refining tests happens in one place, with one history.

This guide is for anyone who needs tests for a function or class, whether you are a developer, a student or a founder who writes a little code. It covers what AI-generated tests are, how to prompt for good test cases, and how to review them.

TL;DR

  • A unit test checks one small piece of code, such as a function, with an input, a call and an expected result. AI is good at drafting these and at listing edge cases.
  • Give the AI your real source file, an existing test file and your framework. Vague prompts produce generic tests.
  • Ask for a list of behaviors first, correct it with your business rules, then generate tests from the approved list.
  • A passing test is not a correct test. In one large study of ChatGPT-written tests, 85.5% of execution failures came from incorrect assertions.
  • Break the code on purpose and rerun. A test that still passes proves nothing.

Table of Contents

What AI-generated unit tests actually are

A unit test exercises a small part of your program in isolation. An academic review of LLM-based test generation describes each test case as three parts: an input configuration, an invocation of the function, and an expected result, called the oracle (ACM Transactions on Software Engineering and Methodology). The oracle is the part that matters most. It is the statement of what the right answer is.

When people search for “test cases AI”, they usually mean the first part: which inputs should I try? AI helps there. IBM’s overview of AI unit testing lists what these tools do: generate assertions and expected outcomes, identify edge cases and negative scenarios, create synthetic data and fixtures, generate mocks for APIs and databases, and help maintain tests as code changes.

The practical benefits are real. Real Python names four: speed, better coverage through edge cases you might not think of, fewer mistakes in repetitive boilerplate, and a way for newer developers to learn testing patterns. It also states the condition: generated tests still need review and refinement.

One case study reported generating nearly 16,000 lines of unit tests, 87 files and 382 test cases, in hours instead of weeks while refactoring, reaching 78.12% branch coverage in targeted logic-heavy modules under developer supervision (arXiv, 2026). The speed is the draw. The supervision is the price of using it safely.

Step 1: Give the AI the right context

The most common reason AI tests are useless is that the AI never saw your code properly. The Vitest documentation spells out what to provide: the actual source file, existing test files from the same project, the test configuration, and type signatures for dependencies you need to mock. Without them, it warns, you get unnecessary imports, wrong environments and useless mocks (Vitest guide).

That advice applies to any language and framework. In practice:

  • Paste the function or class itself, not a description of it.
  • Include one existing test so the output matches your naming, style and helpers.
  • Name the framework (pytest, JUnit, Jest, Vitest) and the version if it matters.
  • State the contract in plain words: what the function should do, including rules that are not visible in the code, such as “discounts above 100% are invalid.”

That last point is where you add value. The model sees what the code does. Only you know what it should do.

If you want a repeatable way to structure these requests, our guide to writing better AI prompts covers the pattern, and the prompt generator can help you build the first version.

Step 2: Ask for test cases before tests

Do not jump to code. First ask the AI to list the behaviors and edge cases for the function, grouped into normal cases, boundaries, invalid input and suspected bugs. Then read the list, delete what is wrong and add the rules only you know. This is the step that separates a useful suite from a decorative one.

A prompt in this shape works for most functions:

Here is my function and one existing test file (below).
Framework: pytest.
List the behaviors this function should have, grouped as:
normal cases, boundaries, invalid input, and anything in the
code that looks like a bug. Do not write any tests yet.

Be specific about what “useful” means. A prompt that asks for tests covering empty input, boundaries, whitespace and unusual characters gets better results than “write tests for this.” The same logic applies to concurrency: if shared state can be touched by several threads, ask for a concurrent test run under a race detector, because a test that checks only a final count can pass by luck (Prompt Architects).

Two more prompt moves are worth the extra minute:

  1. Invariants. Describe a rule such as “the result is always between min and max” and ask for parameterized cases at min, max, one below min and one above max.
  2. A second pass. After the first list, ask the AI to act as a skeptical reviewer and name specific input values that the list misses.

Step 3: Generate tests from the approved list

Now ask for code, and constrain it. Name the framework, require tests of public behavior rather than private details, ask for parameterized tests where several inputs share one rule, and allow mocks only where a dependency does real input or output, such as the network, disk or clock.

A worked example: say you have calculate_total(items, discount_percent). A good request is: “Write pytest tests for calculate_total covering an empty list, a single item, multiple items, 0% and 100% discount, and an invalid discount that should raise a ValueError. Assert exact values.” That prompt tells the model what to cover, what the framework is and what kind of assertion you expect.

Treat the result as a first draft. The Vitest guide recommends refining through conversation, since follow-up prompts often beat a single generation. If the model invents a method that does not exist or misses a mock, tell it so and re-prompt.

If the draft exposes something odd in your function, the bug fix assistant is the natural next stop for diagnosing the problem and fixing the code, without leaving the workspace you wrote the tests in.

Step 4: Run them and sort the failures

Run the suite before you read another line. AI tests often fail for boring reasons: import errors, references to functions that do not exist, wrong setup. The Vitest guide says to always run generated tests before committing for exactly this reason.

The numbers explain why. In the FSE 2024 study of 1,000 ChatGPT-generated tests, only 42.1% compiled and 24.8% ran without errors, and 85.5% of the execution failures were caused by incorrect assertions. The tests that did pass were generally good in sufficiency, readability and usability (arXiv 2305.04207). That study tested an earlier generation of tooling, so treat the percentages as a warning about the failure type rather than a forecast for your own results.

When a test fails, decide which side is wrong:

Failure What it usually means What to do
Import or syntax error The AI guessed at your project layout Paste the correct imports and regenerate
Wrong expected value The AI guessed the oracle Work out the right value by hand from the requirement
Test is right, code fails A real bug Fix the code, not the test
Float comparison fails No tolerance on decimals Use an approximate comparison with a delta

The float row is not hypothetical. In a 2025 comparison of GPT-generated and manual tests, the GPT tests favored mid-range values and had float assertion failures without tolerances, while manual tests used values nearer the edges of each input range (arXiv).

One rule from practitioners deserves emphasis: never let the AI “fix” a failing test by changing production code or by quietly weakening the assertion. Decide first whether the test or the code is wrong.

Step 5: Prove the tests can fail

This is the step most people skip, and it is the one that matters. A generated test derived from the code it tests will pass today and keep passing if the implementation is wrong in the same way tomorrow. Coverage measures what ran, not what was checked (Testing Experience).

Researchers have measured the gap. In an ACM audit of LLM test generators, the tools produced at least one correct, strong test for a bug scenario 63% of the time when given correct code, but only 30% of the time when given buggy code. The authors conclude that a passing LLM-generated suite can give a false sense of security because it verifies the model’s idea of correct, not yours (Correct According to Whom?).

Two checks close that gap:

  • Break the code on purpose. Change a sign, flip a comparison, remove a boundary check, and rerun. If the suite stays green, the tests are not checking that behavior.
  • Run mutation testing. These tools make small automatic changes to your code, called mutants, and report which ones your tests failed to catch. Testing Experience recommends running it on changed files, rejecting tests that kill no mutant, and writing human tests for the survivors based on the requirement.

Then read the assertions themselves:

  1. Is the assertion meaningful? Checking that a result merely exists says almost nothing. Check exact values or key fields.
  2. Where did the expected value come from? If it was recomputed using the same formula as the production code, the same defect sits on both sides. Prefer hand-worked examples.
  3. Does the test target behavior or implementation? Over-mocked tests break on every refactor.
  4. Are there duplicates? Several tests for the same requirement add run time and maintenance without adding safety.

What AI tends to miss

Know the weak spots and you can prompt around them.

A University of Turku study found that Copilot-style generation can produce valid unit tests but inconsistently, with frequent human intervention needed. It struggled with complex mocking and with code of high cyclomatic complexity (many branching paths), while doing well on simple methods (University of Turku). A separate study of JUnit and Mockito tests across ten projects found AI tests reached a mean coverage of about 75% against roughly 60% for manual tests, but manual tests were stronger on critical-path and complex business-logic edge cases (Journal of Computer Fraud & Security).

The pattern is consistent. AI is strong on breadth and boilerplate. You are needed for business rules, domain edge cases and anything that depends on a requirement the code does not state. A human-oversight framework published by the ITEA Journal says the same thing from the other side: boundary conditions, invalid partitions, negative scenarios and concurrency are areas where generative models are underrepresented, and the level of human acceptance should match how critical the system is (ITEA Journal).

IBM adds a useful framing: coverage alone does not guarantee quality, so pair AI-generated tests with other QA practices such as test-driven development, and limit what AI agents can access in sensitive code and data (IBM). If you are weighing how far to trust AI-written code in general, our piece on AI code generation accuracy and security goes deeper.

What AI tends to miss

A repeatable routine

Put the steps together and you get a loop you can run on any function:

  1. Paste the function, one existing test and the framework name.
  2. Ask for behaviors and edge cases, grouped, with no code.
  3. Edit the list: remove wrong items, add your business rules.
  4. Generate parameterized tests from the approved list, asserting exact values.
  5. Run them. Sort failures into test-wrong and code-wrong.
  6. Break the code on purpose, or run mutation testing, and fix gaps.
  7. Review names, mocks, duplicates and where each expected value came from.

On a small function this takes minutes, and every step after the draft is where the quality comes from. Students learning to test can use the same loop as a study tool: the list in step 2 is a quick way to see what a function should handle. Our guide to learning to code with AI shows how to keep the learning in the loop.

Where AmmarAI fits

Where AmmarAI fits

Test drafting is one part of a developer’s week. Docs, code explanations, bug diagnosis and onboarding notes happen alongside it. AmmarAI is one AI workspace with one history and one bill, so the prompt that listed your edge cases is still there when you come back to refine the tests, and the same workspace covers code generation, chat-based brainstorming and document analysis. You can see how that fits developer work on our AI for developers page.

Plans are published on the pricing page: Free at $0 per month with limited usage, Starter at $9.99 per month, Professional at $29.99 per month and Ultimate at $59.99 per month.

Ammarai

The Free plan is enough to run the routine above on your own function and see how the draft, review and refine loop feels in one place.

Our view: tests are a statement of intent

We build AmmarAI around a simple belief: AI should take the repetitive work off your desk, not take the decisions. A unit test is the clearest example. The typing is repetitive. The decision about what correct means is yours.

That is why we think of test generation as a conversation rather than a button. You bring the requirement, the model brings breadth and speed, and you keep the history of what was agreed so the next change starts from there, not from zero.

We also think the most valuable output of an AI test session is often not the tests but the list of behaviors. A reviewed list of edge cases is documentation your team can reuse, and having code, tests and notes in one workspace makes it easy to keep.

Use the model for the first draft, use your judgment for the oracle, and make every test earn its place by showing it can fail.

Ahmed

FAQ

Can AI write unit tests for me?

Yes, it can draft them quickly, especially for functions with clear inputs and outputs. Expect to review and correct them: research on LLM-generated tests shows that incorrect assertions are a leading cause of failures. Treat the output as a first draft that you verify.

What is the best way to get good test cases from AI?

Give it your real source file, an existing test and the framework name, then ask for a grouped list of behaviors before any code. Edit the list to add business rules the model cannot know. Generating tests from that approved list gives far better results than a one-line request.

How do I know if an AI-generated test is correct?

Run it, then break the code on purpose and check that the test fails. Also check that the expected value was worked out by hand or from the requirement, not copied from the code’s own formula. Mutation testing automates the break-it check across a whole file.

Does 100% coverage mean the tests are good?

No. Coverage shows which lines ran, not whether anything was verified. A suite can reach full coverage with weak assertions, so judge tests by whether they fail when the behavior is wrong.

Should I let the AI change my code to make tests pass?

Not without your decision. First work out whether the test or the code is wrong. If the AI weakens an assertion or edits production code to get a green run, the suite stops protecting you.

Sources

Recommended for you

Tools to try next

  • AI Code Generator

    Generate code in multiple languages from natural language descriptions — functions, components, queries and tests, with explanations you can review.

  • AI Agent Builder

    Build agents that run real workflows on a schedule or trigger — reading, deciding and acting without you.

  • AI Social Media Agent

    An agent that plans, writes, schedules and adjusts a month of social posts across your accounts.

Try it on your own work

One AI for everything you create.