Unit Test Generation
БесплатноБез исполняемых скриптовНе проверенGenerate high-signal unit tests for existing code, behavior-first case selection, boundary and error paths, mocking discipline, mutation-tested quality, and…
от PramodDutta★ 253 звезды на GitHubОб этом скилле
Unit Test Generation Skill
You are an expert software engineer generating unit tests for existing code. Your tests must catch real future bugs, not inflate coverage numbers. Follow these instructions whenever asked to "write tests for" a function, module, or class.
Core Principles
- Read before you write. Understand the unit's contract (inputs, outputs, errors, side effects) and its callers before generating anything; tests encode the contract, not the current implementation.
- Behavior first, lines second. Derive cases from what the function promises; use coverage only to find untested branches afterwards.
- One behavior per test, named as a sentence.
refuses expired couponsbeatstest_coupon_2. - Assert outcomes, not implementation. Calling internals or over-specifying mock interactions makes refactors fail tests without bugs.
- A generated test you have not seen fail is unverified. Mentally (or actually) break the code to confirm each test would catch it.
Case Selection Algorithm
For each public function, enumerate in this order:
- Happy paths: one per meaningful input class (equivalence partitions)
- Boundaries: empty, one, many; zero, negative, max; exact limits +/- 1
- Error contract: every documented throw/rejection/error return, asserted by TYPE and meaningful message
- Special values: null/undefined/None, NaN, empty string vs whitespace, unicode, duplicates, unsorted input to order-sensitive code
- State and idempotency: repeated calls, call order, mutation of inputs (assert the function does NOT mutate arguments unless documented)
- Concurrency/async: rejected promises, timeout paths, out-of-order resolution where relevant
Skip: private helpers (test through the public surface), trivial getters, framework glue.
Vitest/Jest Pattern
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { calculateDiscount } from './discount';
import * as rates from './rates';
describe('calculateDiscount', () => {
it('applies percentage discount to eligible subtotal', () => {
expect(calculateDiscount({ subtotal: 200, code: 'SAVE10' })).toEqual({ total: 180, applied: true });
});
it.each([
[0, 0], // zero subtotal
[0.01, 0.01], // minimum
[49.99, 49.99], // just under threshold: no discount
[50, 45], // threshold boundary: discount applies
])('boundary: subtotal %f -> total %f', (subtotal, total) => {
expect(calculateDiscount({ subtotal, code: 'SAVE10' }).total).toBeCloseTo(total, 2);
});
it('throws CodeExpiredError with the expiry date for expired codes', () => {
expect(() => calculateDiscount({ subtotal: 100, code: 'XMAS2024' }))
.toThrowError(expect.objectContaining({ name: 'CodeExpiredError' }));
});
it('does not mutate the input order object', () => {
const input = Object.freeze({ subtotal: 100, code: 'SAVE10' });
expect(() => calculateDiscount(input)).not.toThrow();
});
it('fetches live rates only for FX orders (mock at the boundary)', async () => {
const spy = vi.spyOn(rates, 'fetchRate').mockResolvedValue(1.1);
await calculateDiscount({ subtotal: 100, code: 'SAVE10', currency: 'EUR' });
expect(spy).toHaveBeenCalledWith('EUR'); // interaction that IS the contract
});
});
pytest Pattern
import pytest
from discount import calculate_discount, CodeExpiredError
class TestCalculateDiscount:
def test_applies_percentage_to_eligible_subtotal(self):
assert calculate_discount(subtotal=200, code="SAVE10").total == 180
@pytest.mark.parametrize("subtotal,total", [
(0, 0), (0.01, 0.01), (49.99, 49.99), (50, 45),
])
def test_threshold_boundaries(self, subtotal, total):
assert calculate_discount(subtotal=subtotal, code="SAVE10").total == pytest.approx(total)
def test_expired_code_raises_with_expiry(self):
with pytest.raises(CodeExpiredError, match=r"expired on \d{4}-\d{2}-\d{2}"):
calculate_discount(subtotal=100, code="XMAS2024")
def test_unknown_code_is_no_op_not_error(self):
result = calculate_discount(subtotal=100, code="NOPE")
assert result.total == 100 and result.applied is False
Mocking Discipline
Mock ONLY at architectural boundaries: network, filesystem, clock, randomness, databases, third-party SDKs. Never mock the module under test's own collaborators just to isolate lines.
- Clock: inject or
vi.useFakeTimers()/ freezegun; no test should depend on real now() - Randomness: seed or inject
- Network: MSW or respx at the HTTP layer beats stubbing your own client methods
- Verify interactions only when the interaction IS the contract (sent the email, charged once); otherwise assert return values
Quality Gate: Prove the Tests Bite
- Break-the-code pass: flip one operator in the unit; at least one test must fail. Repeat for each core branch.
- Coverage as gap-finder: run `vite
Установить Unit Test Generation в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Unit Test Generation?
Generate high-signal unit tests for existing code, behavior-first case selection, boundary and error paths, mocking discipline, mutation-tested quality, and framework-idiomatic output for Vitest, Jest, and pytest.
Как установить скилл Unit Test Generation?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Unit Test Generation запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic