Agent skill

Unit Test Generator

by ArabelaTso in ArabelaTso/Skills-4-SE

Automatically generates comprehensive unit tests for functions, classes, and modules.

Apache-2.0Auto-check passedTesting & QA

Install Unit Test Generator

skills CLI
$ npx skills add ArabelaTso/Skills-4-SE --skill unit-test-generator -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install ArabelaTso/Skills-4-SE unit-test-generator --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/unit-test-generator .claude/skills/unit-test-generator && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
unit-test-generator
GitHub stars
253
Token cost
~2.9k tokens
SKILL.md length
848 words
Files
3 (incl. references)
Skills in repo
150
Repo updated
First seen
Licence
Apache-2.0

At a glance

Automatically generates comprehensive unit tests for functions, classes, and modules.

  • Works in 6 steps: Analyze the Code to Test → Identify Test Cases → Examine Existing Test Patterns → …
  • You need to create tests for Python (pytest
  • SKILL.md covers Core Capabilities, Test Generation Workflow, Advanced Patterns and Framework-Specific Guidance, plus 3 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Unit Test Generator is an agent skill from ArabelaTso/Skills-4-SE. Automatically generates comprehensive unit tests for functions, classes, and modules. Use when you need to create tests for Python (pytest, unittest) or Java (JUnit, TestNG) code. Generates tests with comprehensive coverage including happy paths, edge cases, and error conditions. Analyzes existing test patterns in the codebase to match style and conventions. Supports mocking, parameterized tests, fixtures, and follows best practices for each framework.

Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. The skill folder holds 3 other files, including reference files (for example `references/assertion_guide.md` and `references/test_patterns.md`).

It sits in Testing & QA, covering Unit testing. It works with JUnit, pytest, Java and Python. The repository describes itself as: A curated list of 180+ useful Claude Skills for Software Engineering and resources for customizing AI for SE workflows. The licence is Apache-2.0.

When your agent uses it

  • You need to create tests for Python (pytest
  • Tasks that involve Unit testing

Example prompts

  • “/unit-test-generator”

Requirements

  • Python 3

Workflow steps

6 steps, taken from the step headings in SKILL.md.

  1. Analyze the Code to Test
  2. Identify Test Cases
  3. Examine Existing Test Patterns
  4. Generate Test Code
  5. Handle Dependencies and Mocking
  6. Add Documentation and Coverage Summary

What it can do on your machine

Read from SKILL.md and the folder at commit 4f38503. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are python and java).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Unit Test Generator loads about 2.9k tokens when it runs, and up to ~12k if it reads all its reference files. Until then it costs about 119 tokens; SKILL.md has 848 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~119
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~12k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from ArabelaTso/Skills-4-SE at commit 4f38503, republished under its Apache-2.0 licence (© ArabelaTso). 848 words, ~2,863 tokens.

Download SKILL.mdSave it as .claude/skills/unit-test-generator/SKILL.md (or your agent's skills folder). This skill also uses 2 other files; get the full folder from GitHub.
name
unit-test-generator
description
Automatically generates comprehensive unit tests for functions, classes, and modules. Use when you need to create tests for Python (pytest, unittest) or Java (JUnit, TestNG) code. Generates tests with comprehensive coverage including happy paths, edge cases, and error conditions. Analyzes existing test patterns in the codebase to match style and conventions. Supports mocking, parameterized tests, fixtures, and follows best practices for each framework.

Unit Test Generator

Automatically generate comprehensive unit tests for your code.

Core Capabilities

This skill helps you generate high-quality unit tests by:

  1. Analyzing source code - Understanding function/class behavior and contracts
  2. Identifying test cases - Determining happy paths, edge cases, and error conditions
  3. Matching style - Following existing test patterns and conventions in your codebase
  4. Generating tests - Creating complete, runnable test code
  5. Explaining coverage - Documenting what each test validates

Test Generation Workflow

Step 1: Analyze the Code to Test

Examine the source code to understand:

Function Signature:

  • Parameters and their types
  • Return type
  • Exceptions raised

Function Behavior:

  • What the function does
  • Preconditions and postconditions
  • Side effects (DB writes, API calls, file I/O)
  • Dependencies on other code

Example Analysis:

python
def calculate_discount(price: float, discount_percent: float) -> float:
    """Calculate discounted price.

    Args:
        price: Original price (must be positive)
        discount_percent: Discount percentage (0-100)

    Returns:
        Discounted price

    Raises:
        ValueError: If price is negative or discount is invalid
    """
    if price < 0:
        raise ValueError("Price cannot be negative")
    if not 0 <= discount_percent <= 100:
        raise ValueError("Discount must be between 0 and 100")

    return price * (1 - discount_percent / 100)

Analysis:

  • Takes two floats, returns float
  • Validates price >= 0
  • Validates discount in [0, 100]
  • Raises ValueError for invalid inputs
  • Pure function (no side effects)
Step 2: Identify Test Cases

Determine all test scenarios using the Comprehensive Coverage approach:

1. Happy Path Tests - Normal, expected usage

  • Valid inputs that should succeed
  • Typical use cases

2. Edge Case Tests - Boundary conditions

  • Zero values
  • Maximum/minimum values
  • Empty inputs
  • Single element inputs

3. Error Condition Tests - Invalid inputs

  • Null/None values
  • Negative numbers (when positive expected)
  • Out-of-range values
  • Type mismatches (if applicable)
  • Invalid states

4. Special Cases - Domain-specific scenarios

  • Floating point precision
  • String encoding issues
  • Date/time edge cases (leap years, time zones)
  • Concurrency issues

Example Test Cases for calculate_discount:

CategoryTest CaseInputExpected
Happy pathNormal discountprice=100, discount=2080.0
Happy pathNo discountprice=100, discount=0100.0
Happy pathFull discountprice=100, discount=1000.0
Edge caseZero priceprice=0, discount=500.0
Edge caseSmall discountprice=100, discount=0.0199.99
ErrorNegative priceprice=-10, discount=20ValueError
ErrorDiscount too highprice=100, discount=101ValueError
ErrorNegative discountprice=100, discount=-5ValueError
Step 3: Examine Existing Test Patterns

Before generating tests, analyze existing tests in the codebase to match style:

Look for:

  • Test file naming convention (test_*.py, *_test.py, *Test.java)
  • Test class structure (if used)
  • Assertion style (assert, self.assertEqual, assertThat)
  • Fixture/setup patterns
  • Mocking patterns
  • Test organization (Arrange-Act-Assert, Given-When-Then)
  • Naming conventions (test_function_does_something, testFunctionDoesSomething)

Python Example - Analyze Existing Tests:

python
# If existing tests use this pattern:
class TestUserService:
    @pytest.fixture
    def user_service(self):
        return UserService()

    def test_create_user_with_valid_data_succeeds(self, user_service):
        # Arrange
        user_data = {"name": "Alice", "email": "alice@example.com"}

        # Act
        user = user_service.create_user(user_data)

        # Assert
        assert user.name == "Alice"
        assert user.email == "alice@example.com"

Pattern Identified:

  • Class-based test organization
  • pytest fixtures
  • Descriptive test names with underscores
  • Arrange-Act-Assert comments
  • Direct assertions using assert

Java Example - Analyze Existing Tests:

java
// If existing tests use this pattern:
public class UserServiceTest {
    private UserService userService;

    @Before
    public void setUp() {
        userService = new UserService();
    }

    @Test
    public void testCreateUserWithValidData() {
        // given
        UserData data = new UserData("Alice", "alice@example.com");

        // when
        User user = userService.createUser(data);

        // then
        assertEquals("Alice", user.getName());
        assertEquals("alice@example.com", user.getEmail());
    }
}

Pattern Identified:

  • JUnit 4 style with @Before setup
  • Given-When-Then comments
  • assertEquals assertions
  • Test method prefix test
Step 4: Generate Test Code

Create complete, runnable tests following the identified patterns.

Test Structure Template:

1. Test file/class setup
2. Fixtures/setup methods (if needed)
3. Happy path tests
4. Edge case tests
5. Error condition tests
6. Cleanup/teardown (if needed)

Python Example - Generated Tests:

See references/test_patterns.md for full example with 9 comprehensive tests covering happy paths, edge cases, and error conditions.

Java Example - Generated Tests:

See references/test_patterns.md for full JUnit example with comprehensive coverage.

Step 5: Handle Dependencies and Mocking

When the code under test has dependencies (databases, APIs, external services), generate tests with appropriate mocks.

Identify Dependencies:

  • External API calls
  • Database queries
  • File system operations
  • Time/date dependencies
  • Random number generation
  • Other service classes

Python Mocking Pattern:

python
@pytest.fixture
def mock_dependency():
    return Mock()

def test_with_mock(mock_dependency):
    # Arrange
    mock_dependency.method.return_value = expected_value

    # Act
    result = code_under_test(mock_dependency)

    # Assert
    mock_dependency.method.assert_called_once()
    assert result == expected_value

Java Mocking Pattern (Mockito):

java
@Mock
private Dependency dependency;

@Test
public void testWithMock() {
    // given
    when(dependency.method()).thenReturn(expectedValue);

    // when
    Result result = codeUnderTest(dependency);

    // then
    verify(dependency).method();
    assertEquals(expectedValue, result);
}

For detailed mocking examples, see references/test_patterns.md.

Step 6: Add Documentation and Coverage Summary

Include comments explaining:

  • What each test validates
  • Why edge cases are important
  • Coverage achieved

Coverage Summary Example:

python
"""
Test coverage for calculate_discount function:

Happy Path (3 tests):
- Normal discount calculation
- Zero discount (no change)
- Full discount (price becomes 0)

Edge Cases (3 tests):
- Zero price
- Very small discount percentage
- Large price values

Error Conditions (3 tests):
- Negative price
- Discount > 100%
- Negative discount

Total: 9 tests covering all execution paths
"""
Show full SKILL.md (335 more words)Show less

Advanced Patterns

Parameterized Tests

For testing multiple similar scenarios efficiently.

Python (pytest):

python
@pytest.mark.parametrize("price,discount,expected", [
    (100, 20, 80),
    (100, 0, 100),
    (100, 100, 0),
    (50, 10, 45),
    (200, 25, 150),
])
def test_calculate_discount_various_inputs(price, discount, expected):
    result = calculate_discount(price, discount)
    assert result == expected

Java (JUnit 5):

java
@ParameterizedTest
@CsvSource({
    "100.0, 20.0, 80.0",
    "100.0, 0.0, 100.0",
    "100.0, 100.0, 0.0"
})
void testCalculateDiscountVariousInputs(double price, double discount, double expected) {
    assertEquals(expected, calculator.calculateDiscount(price, discount), 0.001);
}
Testing Classes with State

For classes that maintain state across method calls, see references/test_patterns.md for complete examples of:

  • Fixture setup for stateful objects
  • Testing state transitions
  • Testing side effects
  • Cleanup and teardown

Framework-Specific Guidance

Python (pytest)

Key patterns:

  • Use @pytest.fixture for setup/teardown
  • Use @pytest.mark.parametrize for data-driven tests
  • Use pytest.raises() for exception testing
  • Use pytest.approx() for floating point comparisons
  • Use mocker fixture (pytest-mock) for mocking

Test file naming: test_*.py or *_test.py

Python (unittest)

Key patterns:

  • Inherit from unittest.TestCase
  • Use setUp() and tearDown() methods
  • Use self.assertEqual(), self.assertTrue(), etc.
  • Use self.assertRaises() for exceptions
  • Use unittest.mock for mocking
Java (JUnit 4)

Key patterns:

  • Use @Before and @After for setup/teardown
  • Use @Test annotation on test methods
  • Use assertEquals(), assertTrue(), etc.
  • Use @Test(expected = Exception.class) for exceptions
  • Use Mockito for mocking
Java (JUnit 5)

Key patterns:

  • Use @BeforeEach and @AfterEach
  • Use @Test annotation
  • Use assertEquals(), assertThrows(), etc.
  • Use @ParameterizedTest for data-driven tests
  • Use @ExtendWith(MockitoExtension.class) for Mockito

Best Practices

  1. One assertion per test (generally) - Makes failures clear
  2. Test behavior, not implementation - Tests should survive refactoring
  3. Use descriptive test names - Name should explain what and why
  4. Follow AAA pattern - Arrange, Act, Assert (or Given-When-Then)
  5. Keep tests independent - Tests shouldn't depend on each other
  6. Mock external dependencies - Tests should be fast and reliable
  7. Test edge cases - Don't just test the happy path
  8. Use fixtures/setup wisely - Share setup but avoid complex fixtures
  9. Verify error messages - Not just exception type
  10. Keep tests simple - If test is complex, code might be too

Resources

  • references/test_patterns.md - Complete examples for common scenarios (mocking, stateful classes, async code, database operations, file I/O)
  • references/assertion_guide.md - Framework-specific assertion reference and best practices

Quick Reference

ScenarioPython (pytest)Java (JUnit)
Basic testdef test_name():@Test public void testName()
Setup@pytest.fixture@Before (JUnit 4) or @BeforeEach (JUnit 5)
Exception testwith pytest.raises(Error):@Test(expected = Error.class) or assertThrows()
Parameterized@pytest.mark.parametrize@ParameterizedTest
Mockingmocker.patch() or Mock()@Mock with Mockito
Float comparisonpytest.approx()assertEquals(x, y, delta)

© ArabelaTso, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 2 other files (references) in skills/unit-test-generator of ArabelaTso/Skills-4-SE.

  • SKILL.md
  • references/assertion_guide.md
  • references/test_patterns.md

Open the folder on GitHubat commit 4f38503

Compare with similar skills

Unit Test Generator next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Unit Test Generator compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Unit Test Generator this skillArabelaTso/Skills-4-SE253—~2.9kAutomated safety check: PassApache-2.0
Test Analysis Extensionsmicrosoft/testfx1k2 repos~1.1kAutomated safety check: PassMIT
TDD GuideLeoYeAI/openclaw-master-skills2.2k—~1.4kAutomated safety check: PassMIT
TDD Guidealirezarezvani/claude-skills28k—~3.4kAutomated safety check: PassMIT
Assertion Qualitymicrosoft/testfx1k—~4.1kAutomated safety check: PassMIT
Test Gap Analysismicrosoft/testfx1k—~4kAutomated safety check: PassMIT

Similar skills

  • Test Analysis Extensions

    microsoft/testfx

    Official

    Provides file paths to language-specific reference files for the test ANALYSIS skills (assertion-quality, test-anti-patterns, test-gap-analysis, test-smell-detection, test-tagging).

    1k GitHub starsUsed in 2 repos~1.1k tokens
    Testing & QAAuto-check passed
  • TDD Guide

    LeoYeAI/openclaw-master-skills

    Test-driven development skill for writing unit tests, generating test fixtures and mocks, analyzing coverage gaps, and guiding red-green-refactor workflows across Jest, Pytest, JUnit, Vitest, and…

    2.2k GitHub stars~1.4k tokensUpdated 2 mo ago
    Testing & QAAuto-check passed
  • TDD Guide

    alirezarezvani/claude-skills

    Test-driven development skill for writing unit tests, generating test fixtures and mocks, analyzing coverage gaps, and guiding red-green-refactor workflows across Jest, Pytest, JUnit, Vitest, and…

    28k GitHub stars~3.4k tokensUpdated 1 mo ago
    Testing & QAAuto-check passed
  • Assertion Quality

    microsoft/testfx

    Official

    Analyzes the variety and depth of assertions across test suites in any language.

    1k GitHub stars~4.1k tokensUpdated today
    Testing & QAAuto-check passed
  • Test Gap Analysis

    microsoft/testfx

    Official

    Performs pseudo-mutation analysis on production code in any language to find gaps in existing test suites.

    1k GitHub stars~4k tokensUpdated today
    Testing & QAAuto-check passed
  • Test Smell Detection

    microsoft/testfx

    Official

    Deep-dive audit using the full testsmells.org 19-smell academic catalog for tests in any language.

    1k GitHub stars~5.3k tokensUpdated today
    Testing & QAAuto-check passed

More from ArabelaTso/Skills-4-SE

All 150 skills in this repo
  • Framework Migration Assistant

    ArabelaTso/Skills-4-SE

    Automatically migrate Python web applications between frameworks (Flask → FastAPI, Django → FastAPI).

    253 GitHub stars~1.9k tokensUpdated 1 mo ago
    Auto-check passed
  • Metamorphic Test Generator

    ArabelaTso/Skills-4-SE

    Generate test cases using metamorphic testing by applying transformations based on metamorphic properties.

    253 GitHub stars~798 tokensUpdated 1 mo ago
    Auto-check passed
  • Reproduction Trace Instrumenter

    ArabelaTso/Skills-4-SE

    Instruments programs to capture execution traces specifically for reproducing reported bugs, enabling consistent replay and diagnosis of failures.

    253 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Spring Mvc To Boot Migrator

    ArabelaTso/Skills-4-SE

    Automatically migrate Spring MVC applications to Spring Boot.

    253 GitHub stars~2.2k tokensUpdated 1 mo ago
    Auto-check passed
  • State Snapshot Instrumenter

    ArabelaTso/Skills-4-SE

    Instrument programs (Python, C/C++, Java) to capture snapshots of key program states at runtime, including variables, memory, and call stacks.

    253 GitHub stars~2.2k tokensUpdated 1 mo ago
    Auto-check passed

Categories

Questions about Unit Test Generator

What does Unit Test Generator do?

Automatically generates comprehensive unit tests for functions, classes, and modules. Unit Test Generator is an agent skill from ArabelaTso/Skills-4-SE. Automatically generates comprehensive unit tests for functions, classes, and modules.

When should I use Unit Test Generator?

Unit Test Generator fits situations like: you need to create tests for Python (pytest; tasks that involve Unit testing.

How do I install Unit Test Generator in Claude Code?

Run `npx skills add ArabelaTso/Skills-4-SE --skill unit-test-generator -a claude-code`. Or copy the skill folder (skills/unit-test-generator in ArabelaTso/Skills-4-SE) into .claude/skills/unit-test-generator in your project. Claude Code loads it when a task matches its description.

How do I install Unit Test Generator in Codex?

Run `npx skills add ArabelaTso/Skills-4-SE --skill unit-test-generator -a codex`. Or copy the skill folder (skills/unit-test-generator in ArabelaTso/Skills-4-SE) into .agents/skills/unit-test-generator in your project. Codex loads it when a task matches its description.

Can I use Unit Test Generator in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add ArabelaTso/Skills-4-SE --skill unit-test-generator -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/unit-test-generator, .gemini/skills/unit-test-generator, .github/skills/unit-test-generator and .opencode/skills/unit-test-generator in your project.

What does Unit Test Generator need to run?

SKILL.md names no scripts, command-line tools or credentials: Unit Test Generator is instructions for the agent only. Our summary lists: Python 3.

Does Unit Test Generator access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Unit Test Generator safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Unit Test Generator use?

Unit Test Generator is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Unit Test Generator use?

About 2.9k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 9.5k tokens, read only when the agent opens those files.

What are the alternatives to Unit Test Generator?

Skills that share tags, products or a category with Unit Test Generator: Test Analysis Extensions (microsoft/testfx, 1k stars), TDD Guide (LeoYeAI/openclaw-master-skills, 2.2k stars), TDD Guide (alirezarezvani/claude-skills, 28k stars) and Assertion Quality (microsoft/testfx, 1k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Unit Test Generator?

ArabelaTso (a GitHub user) maintains it in ArabelaTso/Skills-4-SE, which has 253 GitHub stars. The repository holds 150 skills in this directory. The repository was last updated on August 21, 2026.

Source: ArabelaTso/Skills-4-SE on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.