🧪 Unit test generation

Quickly generate unit tests covering nominal cases and edge cases for a given function.

Developers hate writing tests. Yet it's one of the areas where AI shines the most: quick generation of a complete suite covering nominal cases, boundary values, errors, and mocks. Used well, it can increase a project's coverage from 30 to 80% in a few hours of work instead of several weeks. The classic pitfall: letting AI generate "happy path" tests that always pass but test nothing critical. This guide presents the workflow for getting robust, targeted tests focused on real bugs.

Step-by-step Workflow
1
Choose the framework and conventions

Tell the AI the test framework (Jest, Vitest, Pytest, JUnit, Go test, RSpec…), project conventions (naming, mocks, fixtures), and expected structure (Arrange-Act-Assert, Given-When-Then).

2
Submit the function to test

Give the AI the function and its minimal context (parameter types, used dependencies). Avoid pasting the whole file — it's more precise and uses fewer tokens.

3
Request nominal cases AND edge cases

Force the AI to explicitly cover: valid input, boundary values (null, empty, max, min), expected errors, async behaviors, side-effects. Without this instruction, AI tends to cover only the happy path.

4
Check actual coverage

Run generated tests and check the coverage report. Identify uncovered branches and have the AI complete them. Iterate 2-3 times to reach 80%+.

5
Review and harden

AI sometimes generates tests that always pass (assertions too permissive, mocks misconfigured). Review each test and verify it actually fails when you break the function. That's the only guarantee it serves a purpose.

Copyable Prompts
Complete test generation
You are an expert in unit testing in [LANGUAGE/FRAMEWORK]. Generate a complete test suite for this function:nn[CODE FUNCTION]nnConstraints:n- Framework: [JEST/VITEST/PYTEST/JUNIT/...]n- Style: Arrange-Act-Assert, one test = one behaviorn- Must cover: (a) nominal cases, (b) boundary values (null, undefined, empty, negative, very large), (c) errors and exceptions, (d) side-effects and mocked callsn- Explicit naming: `should [expected behavior] when [condition]`n- Mocks: use [VITEST MOCK / JEST MOCK / PYTEST FIXTURES]nnProvide the complete test file code, ready to run.
Coverage of missing edge cases
Here is a function and its existing tests:nnFUNCTION:n[CODE]nnEXISTING TESTS:n[CODE TESTS]nnIdentify edge cases NOT covered by existing tests: boundary values, errors, async behaviors, race conditions, shared state. Generate only the additional necessary tests (no duplicates with existing). For each test added, explain in one line why it's important.
REST API test
Generate integration tests for this endpoint in [FRAMEWORK]:nn[CODE ROUTE/CONTROLLER]nnUse [SUPERTEST / PYTEST + REQUESTS / RESTASSURED]. Cover:n- 200 response with valid payloadn- Validation of required fields (400)n- Missing or invalid authentication (401)n- Insufficient permissions (403)n- Resource not found (404)n- Expected server errors (500)n- Business-specific edge cases for this endpointnnMock external dependencies (DB, third-party services).
React hook test
Generate tests for this React hook:nn[CODE HOOK]nnUse __@testing-library/react-hooks__ or __renderHook__ from @testing-library/react depending on version. Cover: initial value, state mutations, side effects (useEffect), cleanup, prop changes, error boundaries if relevant. Provide the complete test file.
Test fixture generation
For this data structure:nn[TYPE / SCHEMA / INTERFACE]nnGenerate test fixtures covering:n- 3 typical valid cases (different to avoid false positives on equality)n- 2 boundary value cases (empty fields, max length, extreme values)n- 2 invalid cases (missing fields, incorrect types)nnOutput format: factory functions or plain exported objects. Explicitly name each fixture.
Recommended tools
Claude Code
★ 4.9 (92) · 20 USD/mois

Assistant de développement IA agentique par Anthropic : comprend votre codebase, édite des fichiers, exécute des commandes et s'intègre à votre environnement de développement.

Why : Génère des suites de tests complètes en comprenant le contexte du projet via CLAUDE.md et la structure du repo.

🤖
Cursor
★ 4.8 (145) · 20 USD/mois

Éditeur de code IA révolutionnaire basé sur VS Code avec agents autonomes

Why : Le mode Composer permet de générer un fichier de tests entier en référençant la fonction cible avec @file.

GitHub Copilot (Copilot X)
★ 4.8 (97) · 10 USD/mois

Assistant IA de développement intégré à l’IDE pour compléter du code, expliquer, générer des fonctions et accélérer le debug.

Why : L'autocomplétion in-IDE est excellente pour compléter des tests cas par cas, intégrée à votre workflow existant.

Estimated ROI
Time Saved
70-80% on initial test writing
Quality Gain
80%+ coverage achievable in hours vs. weeks
Cost
Included in IDE AI subscription (10-20€/month)
Frequently asked questions
Are AI-generated tests reliable?

They're reliable on form (syntax, structure, mocks) but can be misleading on substance: assertions too permissive, missing edge cases, tests that pass even when code is broken. The absolute rule: mutate your code (change a `+` to `-`) and verify tests fail. Otherwise they're useless.

Should tests be written BEFORE code (TDD) with AI?

Yes, it's actually an excellent use case: describe the spec to the AI and have it generate tests. Then ask for the implementation that makes them pass. This reverses the classic pitfall of tests written after the fact to confirm existing code.

Can AI generate E2E tests (Cypress, Playwright)?

Yes, but less effectively than unit tests. E2E tests require knowledge of the DOM, selectors, and wait times that AI can't guess without access to the application. Best: describe the user scenario and provide the HTML/page structure.

How much does a test suite generated by AI cost?

With a Cursor or Claude Code subscription (~20€/month), you can generate several hundred test files per month without exceeding. For massive volumes (legacy code coverage of 100k lines), a batch API approach might cost 50-200€ in tokens, but remains 10x cheaper than the equivalent in human labor.

← Back to guide Développeur