Community编程与开发github.com

测试驱动开发

在实现任何功能或修复缺陷之前,先编写测试用例。

测试驱动开发 是什么?

测试驱动开发 (TDD) 是一种软件工程实践,要求在任何生产代码编写之前,先编写一个会失败的测试。该技能严格遵循“红-绿-重构”循环:编写一个失败的测试(RED),编写最简代码使其通过(GREEN),然后清理代码(REFACTOR)。其核心理念是“如果你没有亲眼看到测试失败,你就不知道它是否测试了正确的东西”。该技能适用于新增功能、缺陷修复、重构和任何行为变更,但排除一次性原型、生成代码和配置文件。它强调“无失败测试,无生产代码”,并要求在确认所有测试通过后,再运行项目的完整测试套件,以确保没有引入回归缺陷。任何形式的“先写代码,后补测试”或“保留现有代码作为参考”都被视为违规,必须删除代码并重新开始。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/obra/superpowers/tree/main/skills/test-driven-development

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

测试驱动开发 (TDD)

概述

先编写测试,看着它失败,再编写最简代码使其通过。

核心原则: 如果你没有亲眼看到测试失败,你就不知道它是否测试了正确的东西。

违反规则的表面形式,就是违反规则的精神实质。

何时使用

始终使用:

  • 新功能
  • 缺陷修复
  • 重构
  • 行为变更

例外情况(请询问你的人类伙伴):

  • 一次性原型
  • 生成的代码
  • 配置文件

想着“就这一次跳过 TDD”?停下来。这是借口。

铁律

没有失败的测试,就不允许有生产代码

先写了代码?删掉,重新开始。

绝无例外:

  • 不要保留作为“参考”
  • 不要在编写测试时“调整”它
  • 不要看它
  • 删除就是删除

完全从测试开始实现。句号。

红-绿-重构

digraph tdd_cycle {
    rankdir=LR;
    red [label="RED\n编写失败测试", shape=box, style=filled, fillcolor="#ffcccc"];
    verify_red [label="确认\n正确失败", shape=diamond];
    green [label="GREEN\n最简代码", shape=box, style=filled, fillcolor="#ccffcc"];
    verify_green [label="确认通过\n全部绿色", shape=diamond];
    refactor [label="REFACTOR\n清理代码", shape=box, style=filled, fillcolor="#ccccff"];
    next [label="下一步", shape=ellipse];

    red -> verify_red;
    verify_red -> green [label="是"];
    verify_red -> red [label="错误\n的失败"];
    green -> verify_green;
    verify_green -> refactor [label="是"];
    verify_green -> green [label="否"];
    refactor -> verify_green [label="保持\n绿色"];
    verify_green -> next;
    next -> red;
}

RED - 编写失败测试

编写一个最小测试,展示应该发生什么。

<好>

test('失败操作重试3次', async () => {
  let attempts = 0;
  const operation = () => {
    attempts++;
    if (attempts < 3) throw new Error('fail');
    return 'success';
  };

  const result = await retryOperation(operation);

  expect(result).toBe('success');
  expect(attempts).toBe(3);
});

名称清晰,测试真实行为,只做一件事 </好>

<坏>

test('重试有效', async () => {
  const mock = jest.fn()
    .mockRejectedValueOnce(new Error())
    .mockRejectedValueOnce(new Error())
    .mockResolvedValueOnce('success');
  await retryOperation(mock);
  expect(mock).toHaveBeenCalledTimes(3);
});

名称模糊,测试的是模拟对象而非代码 </坏>

要求:

  • 只测试一种行为
  • 名称清晰
  • 使用真实代码(除非不得已,否则不用模拟)

验证红色阶段 - 观察失败

必须执行。绝对不能跳过。

npm test path/to/test.test.ts

确认:

  • 测试确实失败(而不是报错)
  • 失败信息符合预期
  • 失败是因为功能缺失(而非拼写错误)

测试通过了? 你在测试已有行为。修改测试。

测试报错了? 修复错误,重新运行直到它正确失败。

绿色阶段 - 最简代码

编写最简代码使测试通过。

<好>

async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
  for (let i = 0; i < 3; i++) {
    try {
      return await fn();
    } catch (e) {
      if (i === 2) throw e;
    }
  }
  throw new Error('unreachable');
}

刚好够用 </好>

<坏>

async function retryOperation<T>(
  fn: () => Promise<T>,
  options?: {
    maxRetries?: number;
    backoff?: 'linear' | 'exponential';
    onRetry?: (attempt: number) => void;
  }
): Promise<T> {
  // YAGNI(你不会需要它)
}

过度设计 </坏>

不要添加功能、重构其他代码或“改进”超出测试范围的东西。

验证绿色阶段 - 观察通过

必须执行。

npm test path/to/test.test.ts

确认:

  • 测试通过
  • 其他测试仍然通过
  • 输出干净(没有错误、警告)

测试失败了? 修复代码,而不是测试。

其他测试失败了? 立即修复。

“其他测试”指的是项目的整个测试套件,而不仅仅是你的文件。 你编写的测试通过并变绿,不代表整个套件是绿色。在宣布修改完成之前,即使你的任务只指定了一个测试文件,也必须运行项目的测试命令(裸 pytest、npm test、cargo test —— 仓库中使用的任何命令)。任务中的范围说明只是界定了交付物,而不是你的验证范围。那次运行中显示的任何失败 —— 哪怕不是你导致的 —— 都必须按名称报告;你亲眼看着测试滚动过去却没提及它,就是报告因遗漏而造假。

重构阶段 - 清理代码

仅在绿色通过后进行:

  • 消除重复
  • 改进命名
  • 提取辅助函数

保持测试绿色。不要添加行为。

重复

下一个针对下一个功能的失败测试。

好的测试

质量好坏
最小只做一件事。名称中出现“和”字?分开。test('验证邮箱和域名和空格')
清晰名称描述行为test('test1')
展示意图演示期望的 API掩盖代码应该做什么

在编写或修改任何测试时,请阅读 writing-good-tests.md 中的规则,这些规则使测试保持诚实:

  • 在编写测试之前,命名会导致测试失败的生产变更
  • 断言真实行为,绝不断言模拟行为
  • 将仅用于测试的代码放在测试工具中,而不是生产类中
  • 在模拟依赖之前理解其副作用

常见借口

借口现实
“太简单了,不需要测试”简单的代码也会出错。测试只需30秒。
“我之后会测试”之后编写的测试立即通过 —— 这什么也证明不了。它们可能测试错了东西,测试的是实现而不是行为,或者漏掉了你忘记的边缘情况。你从未看过它失败,所以从未证明它能捕获这个缺陷。测试优先强制了那种失败。
“之后测试也能达到相同目标(精神而非仪式)”之后测试回答“这段代码做了什么?”;测试优先回答“这段代码应该做什么?”后续编写的测试会受到你已写代码的偏见 —— 你验证的是你记得的情况,而不是你可能发现的情况。覆盖范围却无法证明测试有效。
“已经手动测试过了”手动测试是即兴的:没有记录你覆盖了什么,代码改变后无法重新运行,在压力下容易忘记情况。“我试过它运行了” ≠ 全面。自动化测试每次都以相同方式运行。
“删掉 X 小时的工作太浪费了”沉没成本谬误 —— 不管怎样那段时间已经花掉了。真正的选择是:用 TDD 重写(高信心)vs. 保留代码并在之后附加测试(低信心,很可能有缺陷)。保留你无法信任的代码才是浪费。
“保留作为参考,先写测试”你会调整它的。那是在之后测试。删除就是删除。
“需要先探索”没问题。扔掉探索代码,从 TDD 开始。
“测试难写 = 设计不清晰”聆听测试。难以测试 = 难以使用。
“TDD 会拖慢我”TDD 正是务实之路:在提交前捕捉缺陷,防止回归,让你无忧重构。“务实”的捷径意味着在生产环境中调试 —— 更慢,而不是更快。
“手动测试更快”手动测试不能证明边缘情况。每次修改都得重新测试。
“现有代码没有测试”你正在改进它。为现有代码添加测试。

危险信号 - 停下来重新开始

  • 先写代码,后写测试
  • 先实现,后测试
  • 测试立即通过
  • 无法解释为什么测试失败了
  • “之后”再添加测试
  • 合理化“就这一次”
  • “我已经手动测试过了”
  • “之后测试也能达到相同目的”
  • “重要的是精神而不是仪式”
  • “保留作为参考”或“调整现有代码”
  • “已经花了 X 小时,删掉太浪费”
  • “TDD 是教条的,我很务实”
  • “这次不同,因为……”

所有这些都意味着:删除代码,用 TDD 重新开始。

示例:缺陷修复

缺陷: 接受空邮箱

红色阶段

test('拒绝空邮箱', async () => {
  const result = await submitForm({ email: '' });
  expect(result.error).toBe('请提供邮箱');
});

验证红色阶段

$ npm test
FAIL: 期望 '请提供邮箱',得到 undefined

绿色阶段

function submitForm(data: FormData) {
  if (!data.email?.trim()) {
    return { error: '请提供邮箱' };
  }
  // ...
}

验证绿色阶段

$ npm test
PASS

重构阶段 如果需要,提取多个字段的验证逻辑。

验证清单

在标记工作完成前:

  • 每个新函数/方法都有测试
  • 在实现前亲眼看到每个测试失败
  • 每个测试因预期原因失败(功能缺失,非拼写错误)
  • 编写了最简代码使每个测试通过
  • 所有测试通过
  • 输出干净(没有错误、警告)
  • 测试使用真实代码(只为避免不得已才用模拟)
  • 覆盖了边缘情况和错误

无法勾选所有项?你跳过了 TDD。重新开始。

遇到困难时

问题解决方案
不知道如何测试编写你期望的 API。先写断言。询问你的人类伙伴。
测试太复杂设计太复杂。简化接口。
必须模拟一切代码耦合度太高。使用依赖注入。
测试设置过于庞大提取辅助函数。仍然复杂?简化设计。

与调试集成

发现缺陷?编写一个可以复现它的失败测试。遵循 TDD 循环。测试既证明修复有效,又防止回归。

绝不在没有测试的情况下修复缺陷。

最终规则

生产代码 → 测试存在且首先失败
否则 → 不是 TDD

除非得到你的人类伙伴许可,否则没有例外。

Individual skills in this repo

This repo contains 14 individual skills — each has its own dedicated page.

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).

diagnosing-superpowers

Use when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.

dispatching-parallel-agents

Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies

executing-plans

Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available

finishing-a-development-branch

Use when implementation is complete, all tests pass, and you need to decide how to integrate the work

receiving-code-review

Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation

requesting-code-review

Use when completing tasks, implementing major features, or before merging to verify work meets requirements

subagent-driven-development

Use when executing implementation plans with independent tasks in the current session

systematic-debugging

Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes

using-git-worktrees

Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback

using-superpowers

Use when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions

verification-before-completion

Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always

writing-plans

Use when you have a spec or requirements for a multi-step task, before touching code

writing-skills

Use when creating new skills, editing existing skills, or verifying skills work before deployment

相关技能