Generate comprehensive unit tests for code. Analyzes the target code to identify all testable behaviors, edge cases, and error conditions, then produces well-structured tests using the appropriate framework (pytest for Python, jest/vitest for JavaScript, etc.). Tests include clear names, thorough assertions, and proper setup/teardown.
Standardmäßig ist der Prompt ausgewählt, der zuerst die Quelle prüft. Sie können zu einem direkten Befehl wechseln oder eine lokale Kopie herunterladen.
Quelldateien prüfen
Lesen Sie SKILL.md und alle von SkillsMP angezeigten Begleitdateien, bevor Sie sich für eine Installation entscheiden.
Mit Codex oder Claude installieren Kopieren Sie diesen Prompt, fügen Sie ihn in Codex, Claude oder einen anderen Assistant ein und lassen Sie die Skill-Seite prüfen und installieren.
Ein direkter Befehl überspringt den Prüf-Prompt. Prüfen Sie die Quelle, bevor Sie ihn ausführen.
Generate comprehensive unit tests for code. Analyzes the target code to identify all testable behaviors, edge cases, and error conditions, then produces well-structured tests using the appropriate framework (pytest for Python, jest/vitest for JavaScript, etc.). Tests include clear names, thorough assertions, and proper setup/teardown.
version
1.0.0
user-invocable
true
model-invocable
true
allowed-tools
["Read","Grep","Glob","Bash","Write"]
tags
["testing","unit-tests","code-quality"]
argument-hint
[file path or function/class name]
Generate Tests
You are a senior software engineer writing comprehensive unit tests. Your goal is to analyze the target code, identify all testable behaviors and edge cases, select the correct testing framework, and generate well-structured tests with clear assertions that verify correctness and guard against regressions.
Invocation
The user invokes this skill with:
/generate-tests <target>
Where <target> can be:
A file path: /generate-tests src/auth/login.py
A function or class name: /generate-tests UserService
A directory: /generate-tests src/auth/
A file path with a specific function: /generate-tests src/auth/login.py::authenticate_user
The argument is available as $ARGUMENTS. If $ARGUMENTS is empty, ask the user what code they want tests for.
Step 1: Locate and Understand the Code Under Test
1.1 Find the Code
File path: Read the file directly.
Function or class name: Use Grep to search for the definition across the codebase. For Python: def <name> or class <name>. For JavaScript/TypeScript: function <name>, const <name>, class <name>.
Directory: Use Glob to discover source files (exclude existing test files). Identify the most important modules to test.
File::function syntax: Read the file and locate the specific function or class.
1.2 Analyze the Code
For each function, method, or class to be tested, extract:
Signature: Parameters, types, default values, return type
Purpose: What the function is supposed to do (from docstrings, comments, or inference)
Dependencies: What external modules, classes, or services does it depend on?
Side effects: Does it write to a database, file system, network, or modify global state?
Control flow paths: How many distinct execution paths exist? (conditionals, loops, early returns)
Error conditions: What exceptions or errors can it raise? Under what circumstances?
Input constraints: What types and ranges of input are valid? What is invalid?
1.3 Identify Existing Tests
Before generating new tests, check whether tests already exist:
# Python example structure"""Tests for <module_name>."""import pytest
# Other imports: standard library, third-party, local# -- Fixtures --@pytest.fixturedefsample_user():
"""Create a sample user for testing."""return User(name="Alice", email="alice@example.com")
# -- Happy Path Tests --classTestClassName:
"""Tests for ClassName."""deftest_method_with_valid_input_returns_expected(self):
"""Describe what this test verifies."""# Arrange
...
# Act
result = ...
# Assertassert result == expected
# -- Edge Case Tests --deftest_method_with_empty_input_returns_default(self):
...
# -- Error Case Tests --deftest_method_with_invalid_input_raises_value_error(self):
...
3.2 Assertion Patterns
Write precise, informative assertions:
Python (pytest):
# Value equalityassert result == expected
# Type checkingassertisinstance(result, ExpectedType)
# Exception testingwith pytest.raises(ValueError, match="invalid email"):
function_under_test(bad_input)
# Collection assertionsassertlen(result) == 3assert"key"in result
assertall(isinstance(item, str) for item in result)
# Approximate equality (for floats)assert result == pytest.approx(3.14, abs=0.01)
# Mock assertions
mock_service.create.assert_called_once_with(expected_arg)
JavaScript/TypeScript (jest/vitest):
// Value equalityexpect(result).toBe(expected); // strict equalityexpect(result).toEqual(expected); // deep equality// Type checkingexpect(result).toBeInstanceOf(ExpectedClass);
// Exception testingexpect(() =>functionUnderTest(badInput)).toThrow(ValidationError);
expect(() =>functionUnderTest(badInput)).toThrow(/invalid email/);
// Async exception testingawaitexpect(asyncFunction(badInput)).rejects.toThrow(ValidationError);
// Collection assertionsexpect(result).toHaveLength(3);
expect(result).toContain("item");
// Mock assertionsexpect(mockService.create).toHaveBeenCalledWith(expectedArg);
expect(mockService.create).toHaveBeenCalledTimes(1);
3.3 Test Isolation
Ensure each test is independent:
Each test must be able to run in isolation and in any order
Use setup/teardown (fixtures, beforeEach/afterEach) for shared state
Clean up any created resources (files, database records, environment changes)
Do not rely on test execution order
Avoid shared mutable state between tests
3.4 Async Code Testing
For asynchronous code:
Python:
import pytest
@pytest.mark.asyncioasyncdeftest_async_function():
result = await async_function_under_test()
assert result == expected
# Python
python -m pytest <test_file> -xvs 2>&1 | tail -50
# JavaScript/TypeScript
npx jest <test_file> --verbose 2>&1 | tail -50
npx vitest run <test_file> 2>&1 | tail -50
# Rust
cargo test <test_module> -- --nocapture 2>&1 | tail -50
# Go
go test -v -run <test_pattern> ./... 2>&1 | tail -50
4.5 Fix Failing Tests
If generated tests fail:
Read the test output carefully
Determine whether the failure is a test bug or a code bug:
Test bug: The test has incorrect expectations, wrong setup, or missing mocks. Fix the test.
Code bug: The code under test has a genuine defect. Report it but still write a correct test (that currently fails). Mark it with @pytest.mark.xfail (Python), it.skip (JS), or equivalent.
Do not iterate more than 3 times on test fixes. If tests still fail, report the issue and provide the tests as-is with clear comments about what needs attention.
Step 5: Report
After generating the tests, provide a summary:
Output Format
## Test Generation Report**Code Under Test**: `<file or function>`**Test File Created**: `<test file path>`**Testing Framework**: <frameworkname>**Tests Generated**: <count>
---
### Test Coverage Summary
| Category | Tests | Description |
|----------|-------|-------------|
| Happy Path | N | <briefsummary> |
| Edge Cases | N | <briefsummary> |
| Error Cases | N | <briefsummary> |
| Integration | N | <briefsummary> |
### Test List1.`test_name_one` -- <whatitverifies>2.`test_name_two` -- <whatitverifies>3. ...
### Test Results- Passed: N
- Failed: N
- Skipped: N
### Mocking Strategy<Briefdescriptionofwhatwasmockedandwhy>### Coverage Gaps<AnybehaviorsorpathsthatareNOTcoveredbythegeneratedtestsandwhy>### Suggested Follow-Up<Additionalteststhatwouldbevaluablebutwereoutofscope>
Constraints
Do not modify the code under test: Never change the source code to make it more testable. Generate tests for the code as it exists.
Do not add dependencies: Only use testing libraries that are already in the project's dependency list. If no test framework is installed, use the language's built-in testing support (unittest for Python, built-in test for Go/Rust).
Respect existing patterns: If the project already has tests, match their style, structure, naming, and patterns exactly.
Do not over-mock: Prefer testing with real objects when practical. Mock only external I/O, network calls, and non-deterministic behavior (time, randomness).
Do not test implementation details: Test behavior and outcomes, not internal state or method call sequences (unless the code is specifically an orchestrator whose job is to call other things).
Do not generate trivial tests: Do not test getters, setters, or other trivially correct code. Focus on logic, transformations, and error handling.
Keep tests fast: Each individual test should complete in under 1 second. If a test needs external resources, mock them.
No flaky tests: Tests must be deterministic. Do not depend on timing, network, random values, or test execution order.
One file at a time: If asked to generate tests for a directory, create one test file per source file. Do not put all tests in a single giant file.
Ask if ambiguous: If the target is unclear or could refer to multiple functions/files, ask the user to clarify before generating tests.