关于 test-writer
面向编写单元、集成和端到端测试的开发者技能,指导选择测试类型、按 AAA 组织用例、覆盖边界情况,并生成夹具或模拟数据。
主要功能
- 01编写单元、集成和端到端测试
- 02为待测代码选择测试类型
- 03按准备、执行、断言组织用例
- 04覆盖边界与错误路径
- 05生成测试夹具和模拟数据
适用场景
- 01隔离测试函数或类
- 02检查 API 与数据库交互
- 03验证端到端用户工作流
- 04测试边界情况与失败场景
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ partme-ai/ full-stack-skills --skill test-writer安装后在 Claude Code 中输入/test-writer确认已加载。
详细介绍
何时使用此技能
在用户希望执行以下操作时使用此技能:
- 为函数、类或模块编写单元测试
- 为 API 端点或数据库交互创建集成测试
- 为用户工作流构建端到端测试
- 为边缘情况和错误路径补充测试覆盖率
- 设置测试框架(pytest、Jest、JUnit、Vitest、Playwright)
- 生成测试夹具和模拟数据
如何使用此技能
工作流
- 确定被测代码 - 阅读函数/类/模块,了解其行为
- 选择测试类型 - 单元测试(隔离)、集成测试(多组件)或端到端测试(完整流程)
- 使用 AAA 模式编写测试 - 准备输入、调用函数、断言预期结果
- 覆盖边缘情况 - 空输入、边界值、错误条件、并发访问
单元测试示例(pytest)
import pytest
from decimal import Decimal
from orders import calculate_order_total, OrderItem
class TestCalculateOrderTotal:
def test_single_item_no_discount(self):
items = [OrderItem(price=Decimal("10.00"), quantity=2)]
result = calculate_order_total(items, discount_pct=0.0, tax_rate=0.08)
assert result == Decimal("21.60")
def test_applies_discount_before_tax(self):
items = [OrderItem(price=Decimal("100.00"), quantity=1)]
result = calculate_order_total(items, discount_pct=0.1, tax_rate=0.10)
assert result == Decimal("99.00")
def test_empty_items_returns_zero(self):
result = calculate_order_total([], discount_pct=0.0, tax_rate=0.08)
assert result == Decimal("0.00")
def test_invalid_discount_raises_error(self):
items = [OrderItem(price=Decimal("10.00"), quantity=1)]
with pytest.raises(ValueError, match="discount_pct must be 0-1"):
calculate_order_total(items, discount_pct=1.5)
集成测试示例(Jest + Supertest)
import request from 'supertest';
import { app } from '../src/app';
import { db } from '../src/database';
describe('POST /api/users', () => {
afterEach(async () => { await db.query('DELETE FROM users WHERE email LIKE $1', ['%@test.com']); });
it('creates a user and returns 201', async () => {
const res = await request(app)
.post('/api/users')
.send({ name: 'Alice', email: '[email protected]' })
.expect(201);
expect(res.body).toMatchObject({ name: 'Alice', email: '[email protected]' });
});
it('returns 400 for missing email', async () => {
await request(app).post('/api/users').send({ name: 'Bob' }).expect(400);
});
});
最佳实践
- 每种行为只做一个断言 - 每个测试都应验证一种具体行为
- 使用描述性测试名称 - 将测试命名为
test_<behavior>_when_<condition>或it('should <outcome> when <input>') - 隔离依赖项 - 对外部服务、数据库和 API 使用模拟对象/桩
- 测试契约,而非实现 - 断言输出和副作用,而不是内部状态
- 在 CI 中运行测试 - 确保每次提交时测试都能通过;关键路径的行覆盖率应达到 80% 以上
关键词
测试编写, test writing, unit test, integration test, e2e test, pytest, Jest, JUnit, Vitest, Playwright, mock, fixture, 单元测试, 集成测试, 端到端测试, test coverage
评论
支持 Markdown