Best AI tools for generating useful unit tests

Compare Copilot, Cursor and Claude Code for useful unit tests, with an executed Python exercise and checks for meaningful assertions and regressions.

A developer reviews unit test results

A useful unit test does more than pass: it fails when important behaviour becomes wrong. Choose an AI test-writing tool by the errors its tests detect, the clarity of its assertions and their maintenance cost, rather than the number of files generated. GitHub Copilot, Cursor and Claude Code offer three starting points, depending on how your team works.

This guide separates documented capabilities from an original exercise executed locally. It is not a ranking based on hands-on comparative testing of those products. The exercise gives you a consistent way to evaluate suggestions against one business rule before allowing broader changes to a project.

Which tool fits your project?

GitHub Copilot: start in your existing editor

GitHub documents generating unit tests with Copilot Chat from a function and expected cases. If your team already uses GitHub Copilot, begin with a small representative module. Our selection criterion is understandable assertions that match the existing framework, without adopting an entirely new working environment just for this task.

Cursor: work across project files

Cursor documents a coding agent for working with a codebase and checking changes. This approach may suit tests that require context from several files. To evaluate it, set a boundary: propose the tests, explain dependencies and show changes. Reject a rewrite of the production function whose only purpose is making a test failure disappear.

Claude Code: organise a verification loop

Claude Code can identify missing test cases and write tests that follow the conventions of your project. It is a candidate for teams that want to direct these steps from their development environment. Request the case plan, implementation and authorised execution as separate stages. Our recommendation concerns that working discipline, not a measured claim that one model writes better tests.

Define behaviour before requesting tests

An assistant reading only the implementation can turn an existing bug into an expected result. Supply an independent business rule: “Shipping is free for an order worth at least 50 euros, including the boundary, or for a member. Otherwise it costs 4.90 euros. Reject a negative order value.” Represent money as integer cents. Valid input types are a precondition in this exercise; it is not a complete public API validation specification.

Also provide the existing test command, an example test file and the authorised scope of edits. Separate established behaviour from open questions. If refunds are undefined, the assistant should identify that uncertainty rather than invent a policy. A product owner settles the rule; a test then expresses the decision. This prevents a plausible-looking suite from quietly becoming an unreviewed specification.

Executed exercise: a small shipping-fee function

Here is our deliberately short reference implementation. It is not an output obtained while testing Copilot, Cursor or Claude Code. We executed the six cases below locally in Python on 13 November 2026, then ran them against three variants containing one deliberately introduced error each.

def fee(total, member):
    if total < 0:
        raise ValueError("negative total")
    return 0 if member or total >= 5000 else 490
  • 0 cents, non-member: 490.
  • 4,999 cents, non-member: 490.
  • 5,000 cents, non-member: 0.
  • 5,001 cents, non-member: 0.
  • 1,000 cents, member: 0.
  • −1 cent, non-member: ValueError.

The reference passes all six cases. Replacing “greater than or equal to” with “greater than” fails the 5,000-cent case. Removing the membership benefit fails the 1,000-cent member case. Removing the negative-value check fails the final case. Each faulty variant passes five out of six: the suite detects all three selected errors, without proving that every other possible bug is absent.

This is a small test-sensitivity exercise, not a product benchmark or a measurement of application-wide coverage. For an actual selection, give each candidate exactly the same rule and code, preserve its response and run its proposed tests without silently repairing the assertions. Record any human changes separately so the comparison remains meaningful.

A prompt that avoids decorative tests

Read the business rule and the specified module. First propose cases with inputs, expected outcomes and reasons. Use our existing framework. Do not change production code. Assert observable results, not incidental implementation details. Flag undefined behaviour. After review, run only the authorised test command and report the command, outcome and remaining errors. Do not disable tests to obtain a passing result.

Add repository-specific constraints: no network access, no customer records, no paid services and no extra installations without approval. A unit test should check a small unit of behaviour. Sending a real email or charging an account is unnecessary for this exercise. Checks involving real external services belong in a separately approved environment and testing strategy.

What makes an assertion useful?

“The result exists” is too weak to verify a fee. “The result equals 490 for a non-member below the threshold” expresses a specific behaviour. Avoid calculating the expected answer with the same formula as the implementation: both may reproduce the same mistake. Use explicit values for critical cases and names that explain which business rule each test protects.

False failures also matter. A test coupled to an internal call order may break after a refactor even though user-visible behaviour is unchanged. Ask whether the order really forms part of the contract. Keep necessary checks, remove valueless assumptions and document the decision. Simply deleting an inconvenient test is not a reliable response.

A practical comparison scorecard

  1. Execution: do the tests run using the tools already installed?
  2. Relevance: does every case correspond to a rule or identified risk?
  3. Sensitivity: which deliberate defects are actually detected?
  4. Stability: do repeated runs produce the same outcome?
  5. Maintenance: can a colleague understand a failure without rereading the whole conversation?

Record human corrections and review time, not just generation time. A shorter proposal can be better if it covers meaningful boundaries without twenty redundant variations. Line coverage can identify code that has not been exercised; alone, it does not prove that the right values were asserted. Keep the distinction between executing a statement and checking its effect.

When comparing cost, use the same finished task: a reviewed, runnable set of tests accepted by the team. Include time spent correcting imports, fixtures and overcomplicated mocks. Do not treat a large generated suite as free progress if it creates a maintenance burden. One clear regression test can be more valuable than dozens of assertions on private details.

Before integrating the result

Review the entire diff, confirm that configuration changes have not excluded difficult tests and rerun the existing suite. Keep fictional inputs alongside the exercise. For broader environment selection, see our comparison of Cursor and GitHub Copilot in an existing codebase. Here the narrower decision is which tool helps your team detect an explainable regression at an acceptable verification cost.

Our starting recommendation is to evaluate the assistant you already have on one function. Switch when a concrete weakness remains, not because another product promises more tests. Features, quotas and terms change, so check the applicable plan before buying. A small reviewed and executed batch is stronger than mass generation whose failures nobody understands.

Complete test script to copy

Save the following code as exercise.py and run python exercise.py (or python3 exercise.py). It uses only the standard library and fictional amounts in cents, with no network calls or external dependencies. Keep assertions enabled: do not run Python with -O.

import json,sys
# Original reference exercise; these are not outputs of the compared products.
def fee(total,member):
    if total < 0: raise ValueError('negative total')
    return 0 if member or total >= 5000 else 490

def boundary_bug(total,member):
    if total < 0: raise ValueError('negative total')
    return 0 if member or total > 5000 else 490

def membership_bug(total,member):
    if total < 0: raise ValueError('negative total')
    return 0 if total >= 5000 else 490

def negative_bug(total,member):
    return 0 if member or total >= 5000 else 490
cases=[(0,False,490),(4999,False,490),(5000,False,0),(5001,False,0),(1000,True,0),(-1,False,'ValueError')]
report={}
for fn in [fee,boundary_bug,membership_bug,negative_bug]:
 results=[]
 for total,member,expected in cases:
  try: actual=fn(total,member)
  except ValueError: actual='ValueError'
  results.append({'total':total,'member':member,'expected':expected,'actual':actual,'pass':actual==expected})
 report[fn.__name__]={'passed':sum(r['pass'] for r in results),'cases':results}
assert report['fee']['passed']==6
assert all(report[k]['passed']==5 for k in ['boundary_bug','membership_bug','negative_bug'])
print(json.dumps({'python':sys.version.split()[0],'report':report},indent=2))

Expected result: fee passes six cases; each of the three intentionally faulty variants passes five. The script stops with an error if these expectations are not met. We reran it before publication. This educational test does not measure Copilot, Cursor or any other assistant.

Related tools