Skip to content
CodingIntermediate

Write unit tests for a function

A prompt that writes unit tests covering normal cases, edge cases and invalid input, with a one-line comment for each, plus an example and tips.

Last reviewed

The prompt

Write unit tests for the function below using [test framework]. Cover normal cases, edge cases and invalid input. Add a one-line comment explaining each test.

Function:
[paste here]

Why it works: Listing the case types gives you better coverage than just "write tests".

Works in ChatGPT, Claude and Gemini

When to use it

Use this when you have a working function and want a safety net before you change it, or when a function has no tests at all. The prompt names the kinds of case to cover, which is what makes the tests useful and not just a list of happy paths.

How to use it

  1. Name your test framework, such as pytest, Jest or JUnit, and paste the function.
  2. Run the tests. Any failure is either a bug in the function or a wrong test, and both are worth knowing.
  3. Read each test and its comment. Delete tests that check nothing useful and add any case you know matters.

A filled-in example

prompt
Write unit tests for the function below using pytest. Cover normal cases, edge cases and invalid input. Add a one-line comment explaining each test.

Function:
def percentage(part, whole):
    return part / whole * 100

Ways to adapt it

  • Name the edge cases you fear. "Include empty input, negative numbers and very large values."
  • Ask for table-driven tests. "Use parameterised tests" keeps them short.
  • Add a behaviour rule. "Division by zero should raise a clear error" tells it what correct looks like.
  • Review the gaps. "What cases did you not cover?" is a useful follow-up.

Mistakes to avoid

  • Treating generated tests as proof. They only check what the AI thought to check. A passing test is not a correct function.
  • Tests that copy the bug. If the AI assumes the function is right, its tests may agree with a mistake. State the intended behaviour.
  • Skipping the run. Always run them. Generated tests sometimes contain errors of their own.

More prompts to try

Keep reading