From test-generator
分析源代码并生成对应的单元测试用例。 当用户说"生成测试"、"写单元测试"、"添加测试用例"、"测试覆盖"、"单元测试"、"vitest测试"、"jest测试"、"pytest测试"、"测试代码"时使用此技能。 支持多种语言和框架:JavaScript/TypeScript (Jest, Vitest, Mocha)、Python (pytest, unittest)、Java (JUnit 5, TestNG)。 自动生成:正常流程测试、边界条件测试、异常情况测试、Mock 配置。输出遵循 AAA 模式的高质量测试代码。
How this skill is triggered — by the user, by Claude, or both
Slash command
/test-generator:test-generationThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
这个技能负责分析源代码并生成对应的单元测试用例。支持多种编程语言和测试框架。
这个技能负责分析源代码并生成对应的单元测试用例。支持多种编程语言和测试框架。
# 生成单个函数的测试
/test src/utils/calculator.js --function add --framework vitest
# 生成整个文件的测试
/test src/services/userService.js --framework jest --mocks
# 包含覆盖率分析
/test src/api/userController.js --framework jest --coverage
# 生成边界值测试
/test src/utils/validator.js --edge-cases
# 只生成异常测试
/test src/services/payment.js --error-only
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { UserService } from '../src/services/UserService';
describe('UserService', () => {
let userService: UserService;
let mockDb: any;
beforeEach(() => {
mockDb = {
find: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn()
};
userService = new UserService(mockDb);
});
describe('getUserById', () => {
it('should return user when found', async () => {
// Arrange
const userId = '123';
const expectedUser = { id: userId, name: 'John' };
mockDb.find.mockResolvedValue(expectedUser);
// Act
const result = await userService.getUserById(userId);
// Assert
expect(result).toEqual(expectedUser);
expect(mockDb.find).toHaveBeenCalledWith({ id: userId });
});
it('should return null when user not found', async () => {
// Arrange
const userId = '999';
mockDb.find.mockResolvedValue(null);
// Act
const result = await userService.getUserById(userId);
// Assert
expect(result).toBeNull();
});
});
});
import pytest
from unittest.mock import Mock, patch
from services.user_service import UserService
class TestUserService:
@pytest.fixture
def user_service(self):
with patch('services.user_service.Database') as mock_db:
yield UserService(mock_db)
def test_get_user_by_id_success(self, user_service):
"""Test getting user with valid ID"""
# Arrange
user_id = 123
expected_user = {"id": user_id, "name": "John"}
user_service.db.find.return_value = expected_user
# Act
result = user_service.get_user_by_id(user_id)
# Assert
assert result == expected_user
user_service.db.find.assert_called_once_with({"id": user_id})
def test_get_user_by_id_not_found(self, user_service):
"""Test getting non-existent user"""
# Arrange
user_id = 999
user_service.db.find.return_value = None
# Act
result = user_service.get_user_by_id(user_id)
# Assert
assert result is None
// 根据类型生成测试数据
const testData = {
string: ["hello", "", "a".repeat(255), "特殊字符"],
number: [0, 1, -1, 100, Number.MAX_SAFE_INTEGER],
boolean: [true, false],
array: [[], [1], [1, 2, 3], Array(1000).fill(0)],
object: [{}, { key: "value" }, null, undefined]
};
// 边界值生成
const boundaries = {
string: ["", "a", "a".repeat(255), "a".repeat(256)],
number: [Number.MIN_VALUE, -1, 0, 1, Number.MAX_VALUE],
array: [[] , [1], [1000]],
};
// 自动生成的Mock
jest.mock('../src/utils/logger', () => ({
logger: {
info: jest.fn(),
error: jest.fn(),
warn: jest.fn()
}
}));
// 测试中验证Mock调用
expect(logger.info).toHaveBeenCalledWith('User created successfully');
// ✅ 好的命名
it('should create user with valid data');
it('should throw error when email already exists');
// ❌ 避免的命名
it('test1');
it('user creation test');
it('should calculate discount correctly', () => {
// Arrange - 准备测试数据
const price = 100;
const discountRate = 0.1;
// Act - 执行被测代码
const result = calculateDiscount(price, discountRate);
// Assert - 验证结果
expect(result).toBe(90);
});
// ✅ 具体的断言
expect(user.email).toMatch(/^[^\s@]+@[^\s@]+\.[^\s@]+$/);
// ❌ 模糊的断言
expect(user).toBeDefined();
// Promise
it('should resolve with data', async () => {
const result = await fetchData();
expect(result).toEqual(expectedData);
});
// Callback
it('should call callback', (done) => {
fetchData((data) => {
expect(data).toBeDefined();
done();
});
});
it('should throw error for invalid input', () => {
expect(() => validateEmail('invalid')).toThrow();
});
it('should reject promise on error', async () => {
await expect(asyncOperation()).rejects.toThrow('Error message');
});
// 使用假时间
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('should debounce function calls', async () => {
const debouncedFn = debounce(originalFn, 100);
debouncedFn();
vi.advanceTimersByTime(50);
expect(originalFn).not.toHaveBeenCalled();
vi.advanceTimersByTime(50);
expect(originalFn).toHaveBeenCalledTimes(1);
});
这个技能与其他命令集成:
/test - 生成测试用例/mock - 生成Mock数据/coverage - 分析测试覆盖率通过智能分析和模板化生成,帮助开发者快速编写高质量的单元测试。
npx claudepluginhub protagonistss/ithinku-plugins --plugin test-generatorGenerates unit tests matching project patterns and frameworks like Jest/Vitest (JS/TS), pytest (Python), Go testing, JUnit (Java), RSpec (Ruby).
Generates unit tests from source code for JS/TS (Jest/Vitest/Mocha), Python (pytest), Java (JUnit 5), Go, covering happy paths, edges, boundaries, errors with mocks.
Generates unit tests for code or functions, analyzing inputs, paths, edges, and errors. Detects project test framework (pytest, Jest, etc.), applies mocks, matches style, and writes files after confirmation.