arabelatso/unit-test-generator
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.
npx skills add https://github.com/ArabelaTso/Skills-4-SE --skill unit-test-generator
Automatically generate comprehensive unit tests for your code.
This skill helps you generate high-quality unit tests by:
Examine the source code to understand:
Function Signature:
Function Behavior:
Example Analysis:
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:
Determine all test scenarios using the Comprehensive Coverage approach:
1. Happy Path Tests - Normal, expected usage
2. Edge Case Tests - Boundary conditions
3. Error Condition Tests - Invalid inputs
4. Special Cases - Domain-specific scenarios
Example Test Cases for calculate_discount:
| Category | Test Case | Input | Expected |
|----------|-----------|-------|----------|
| Happy path | Normal discount | price=100, discount=20 | 80.0 |
| Happy path | No discount | price=100, discount=0 | 100.0 |
| Happy path | Full discount | price=100, discount=100 | 0.0 |
| Edge case | Zero price | price=0, discount=50 | 0.0 |
| Edge case | Small discount | price=100, discount=0.01 | 99.99 |
| Error | Negative price | price=-10, discount=20 | ValueError |
| Error | Discount too high | price=100, discount=101 | ValueError |
| Error | Negative discount | price=100, discount=-5 | ValueError |
Before generating tests, analyze existing tests in the codebase to match style:
Look for:
test_*.py, *_test.py, *Test.java)assert, self.assertEqual, assertThat)test_function_does_something, testFunctionDoesSomething)Python Example - Analyze Existing Tests:
# 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": "[email protected]"}
# Act
user = user_service.create_user(user_data)
# Assert
assert user.name == "Alice"
assert user.email == "[email protected]"
Pattern Identified:
assertJava Example - Analyze Existing Tests:
// 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", "[email protected]");
// when
User user = userService.createUser(data);
// then
assertEquals("Alice", user.getName());
assertEquals("[email protected]", user.getEmail());
}
}
Pattern Identified:
@Before setupassertEquals assertionstestCreate 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.
When the code under test has dependencies (databases, APIs, external services), generate tests with appropriate mocks.
Identify Dependencies:
Python Mocking Pattern:
@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):
@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.
Include comments explaining:
Coverage Summary Example:
"""
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
"""
For testing multiple similar scenarios efficiently.
Python (pytest):
@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):
@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);
}
For classes that maintain state across method calls, see references/test_patterns.md for complete examples of:
Key patterns:
@pytest.fixture for setup/teardown@pytest.mark.parametrize for data-driven testspytest.raises() for exception testingpytest.approx() for floating point comparisonsmocker fixture (pytest-mock) for mockingTest file naming: test_*.py or *_test.py
Key patterns:
unittest.TestCasesetUp() and tearDown() methodsself.assertEqual(), self.assertTrue(), etc.self.assertRaises() for exceptionsunittest.mock for mockingKey patterns:
@Before and @After for setup/teardown@Test annotation on test methodsassertEquals(), assertTrue(), etc.@Test(expected = Exception.class) for exceptionsKey patterns:
@BeforeEach and @AfterEach@Test annotationassertEquals(), assertThrows(), etc.@ParameterizedTest for data-driven tests@ExtendWith(MockitoExtension.class) for Mockito10. Keep tests simple - If test is complex, code might be too
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| Scenario | Python (pytest) | Java (JUnit) |
|----------|----------------|--------------|
| Basic test | def test_name(): | @Test public void testName() |
| Setup | @pytest.fixture | @Before (JUnit 4) or @BeforeEach (JUnit 5) |
| Exception test | with pytest.raises(Error): | @Test(expected = Error.class) or assertThrows() |
| Parameterized | @pytest.mark.parametrize | @ParameterizedTest |
| Mocking | mocker.patch() or Mock() | @Mock with Mockito |
| Float comparison | pytest.approx() | assertEquals(x, y, delta) |
Take arabelatso/unit-test-generator from the repository into ~/.claude/skills for personal
use, or into .claude/skills inside a project.
The agent identifies a skill by the name field in its header. Two skills with the
same name cannot sit side by side — one of them will be ignored.