test-driven-development
通过 red-green-refactor 循环用测试驱动开发。用于实现任何逻辑、修复任何 bug,或改变任何行为。用于需要证明代码能工作、收到 bug 报告,或即将修改现有功能时。
vinvcn · Static checks on file
Installation
Read the source and dependencies before running a command. Copying does not install or execute anything.
npx skills add vinvcn/addyosmani-agent-skills-zh --skill test-driven-developmentAbout this skill
name: test-driven-development description: 通过 red-green-refactor 循环用测试驱动开发。用于实现任何逻辑、修复任何 bug,或改变任何行为。用于需要证明代码能工作、收到 bug 报告,或即将修改现有功能时。
Test-Driven Development
概览
先写一个失败测试,再写让它通过的代码。修 bug 时,在尝试修复前先用测试复现 bug。测试是证据,“看起来对”不算完成。拥有良好测试的代码库是 AI agent 的超能力;没有测试的代码库则是一种负债。
何时使用
- 实现任何新逻辑或行为
- 修复任何 bug(Prove-It Pattern)
- 修改现有功能
- 添加边界情况处理
- 任何可能破坏现有行为的变更
何时不要使用: 纯配置变更、文档更新,或没有行为影响的静态内容变更。
相关: 对基于浏览器的变更,将 TDD 与使用 Chrome DevTools MCP 的运行时验证结合使用。见下方 Browser Testing 部分。
先发现技术栈
TDD 循环是通用的;命令不是。在写第一个测试之前,先弄清楚这个仓库是怎么测试的,并在每个 RED、GREEN 和验证步骤使用它自己的命令:
- 语言与构建系统 ——
package.json、pom.xml/build.gradle、pyproject.toml、go.mod、Cargo.toml、Gemfile、Makefile - 仓库内置的 wrapper —— 优先用
./gradlew、./mvnw、make test或仓库脚本,而不是全局安装的工具 - 测试框架与配置 —— 以及它如何运行单个聚焦测试 vs 完整套件
- 现有约定 —— 测试放在哪里、文件怎么命名、相邻测试遵循什么模式
- 已记录的命令 —— README、CONTRIBUTING 和 CI workflows 展示的是真正把关合并的命令
在循环中运行仓库的聚焦测试命令,在完成前运行它的完整套件命令。绝不要假设 npm test 这类默认值;Gradle、Cargo 或 pytest 项目都有各自的等价命令。
下面的示例用 TypeScript 演示;一旦你发现了项目自己的工具链,这个工作流在任何语言里都完全相同。
TDD 循环
RED GREEN REFACTOR
Write a test Write minimal code Clean up the
that fails ──→ to make it pass ──→ implementation ──→ (repeat)
│ │ │
▼ ▼ ▼
Test FAILS Test PASSES Tests still PASS
步骤 1:RED,编写失败测试
先写测试。它必须失败。一个立即通过的测试什么都证明不了。
// RED: This test fails because createTask doesn't exist yet
describe('TaskService', () => {
it('creates a task with title and default status', async () => {
const task = await taskService.createTask({ title: 'Buy groceries' });
expect(task.id).toBeDefined();
expect(task.title).toBe('Buy groceries');
expect(task.status).toBe('pending');
expect(task.createdAt).toBeInstanceOf(Date);
});
});
步骤 2:GREEN,让它通过
编写最少代码让测试通过。不要过度工程化:
// GREEN: Minimal implementation
export async function createTask(input: { title: string }): Promise<Task> {
const task = {
id: generateId(),
title: input.title,
status: 'pending' as const,
createdAt: new Date(),
};
await db.tasks.insert(task);
return task;
}
步骤 3:REFACTOR,清理
测试保持绿色后,在不改变行为的前提下改进代码:
- 抽取共享逻辑
- 改进命名
- 移除重复
- 必要时优化
每个重构步骤后都运行测试,确认没有破坏任何东西。
Prove-It Pattern(Bug 修复)
收到 bug 报告时,不要从尝试修复开始。 先写一个能复现它的测试。
Bug report arrives
│
▼
Write a test that demonstrates the bug
│
▼
Test FAILS (confirming the bug exists)
│
▼
Implement the fix
│
▼
Test PASSES (proving the fix works)
│
▼
Run full test suite (no regressions)
示例:
// Bug: "Completing a task doesn't update the completedAt timestamp"
// Step 1: Write the reproduction test (it should FAIL)
it('sets completedAt when task is completed', async () => {
const task = await taskService.createTask({ title: 'Test' });
const completed = await taskService.completeTask(task.id);
expect(completed.status).toBe('completed');
expect(completed.completedAt).toBeInstanceOf(Date); // This fails → bug confirmed
});
// Step 2: Fix the bug
export async function completeTask(id: string): Promise<Task> {
return db.tasks.update(id, {
status: 'completed',
completedAt: new Date(), // This was missing
});
}
// Step 3: Test passes → bug fixed, regression guarded
测试金字塔
按金字塔分配测试投入:大多数测试应该小而快,越往高层测试越少:
╱╲
╱ ╲ E2E Tests (~5%)
╱ ╲ Full user flows, real browser
╱──────╲
╱ ╲ Integration Tests (~15%)
╱ ╲ Component interactions, API boundaries
╱────────────╲
╱ ╲ Unit Tests (~80%)
╱ ╲ Pure logic, isolated, milliseconds each
╱──────────────────╲
The Beyonce Rule: 你依赖什么,就应该给什么写测试。基础设施变更、重构和迁移不负责替你抓 bug,你的测试才负责。如果一次变更破坏了你的代码,而你恰好没有为它写测试,那责任在你。
测试大小(资源模型)
除了金字塔层级,还要按测试消耗的资源分类:
| 大小 | 约束 | 速度 | 示例 |
|---|---|---|---|
| Small | 单进程,无 I/O,无网络,无数据库 | 毫秒级 | 纯函数测试、数据转换 |
| Medium | 可多进程,仅 localhost,无外部服务 | 秒级 | 带测试 DB 的 API 测试、组件测试 |
| Large | 可多机器,允许外部服务 | 分钟级 | E2E 测试、性能 benchmark、staging 集成 |
Small tests 应该占据测试套件的大多数。它们快速、可靠,并且失败时易于调试。
决策指南
Is it pure logic with no side effects?
→ Unit test (small)
Does it cross a boundary (API, database, file system)?
→ Integration test (medium)
Is it a critical user flow that must work end-to-end?
→ E2E test (large) — limit these to critical paths
编写好测试
测试状态,而不是交互
断言操作的结果,而不是内部调用了哪些方法。验证方法调用顺序的测试会在你重构时破坏,即使行为没有变化。
// Good: Tests what the function does (state-based)
it('returns tasks sorted by creation date, newest first', async () => {
const tasks = await listTasks({ sortBy: 'createdAt', sortOrder: 'desc' });
expect(tasks[0].createdAt.getTime())
.toBeGreaterThan(tasks[1].createdAt.getTime());
});
// Bad: Tests how the function works internally (interaction-based)
it('calls db.query with ORDER BY created_at DESC', async () => {
await listTasks({ sortBy: 'createdAt', sortOrder: 'desc' });
expect(db.query).toHaveBeenCalledWith(
expect.stringContaining('ORDER BY created_at DESC')
);
});
测试中 DAMP 优于 DRY
在生产代码中,DRY(Don't Repeat Yourself)通常是对的。在测试中,DAMP(Descriptive And Meaningful Phrases) 更好。测试应该读起来像规格说明;每个测试都应该讲完整故事,而不需要读者追踪共享 helper。
// DAMP: Each test is self-contained and readable
it('rejects tasks with empty titles', () => {
const input = { title: '', assignee: 'user-1' };
expect(() => createTask(input)).toThrow('Title is required');
});
it('trims whitespace from titles', () => {
const input = { title: ' Buy groceries ', assignee: 'user-1' };
const task = createTask(input);
expect(task.title).toBe('Buy groceries');
});
// Over-DRY: Shared setup obscures what each test actually verifies
// (Don't do this just to avoid repeating the input shape)
当重复能让每
Read the complete source ↗