tdd

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Test-Driven Development

测试驱动开发

Iron Law

铁律

NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST

Cycle

流程

RED — Write a failing test

RED — 编写失败的测试用例

Write a test that defines the expected behavior BEFORE writing any production code.
  • The test MUST fail before you write production code
  • If the test passes without any changes, your test is wrong — rewrite it
  • The test should describe behavior, not implementation
在编写任何生产代码之前,先编写定义预期行为的测试用例。
  • 在编写生产代码前,测试必须失败
  • 如果无需修改代码测试就通过了,说明你的测试用例存在问题 — 重写它
  • 测试用例应描述行为,而非实现细节

GREEN — Write the minimum production code

GREEN — 编写最小化的生产代码

Write the minimum production code to make the test pass.
  • Do NOT write more than necessary
  • Do NOT optimize
  • Do NOT refactor
  • Ugly code that passes is correct at this stage
编写最少的生产代码使测试用例通过。
  • 不要编写超出必要的代码
  • 不要进行优化
  • 不要进行重构
  • 此时只要能通过测试,代码丑陋也没关系

REFACTOR — Clean up without changing behavior

REFACTOR — 在不改变行为的前提下优化代码

Improve the code while keeping all tests green.
  • All tests must still pass after refactoring
  • Improve naming, extract functions, remove duplication
  • If any test fails after refactoring, your refactor changed behavior — revert
在保持所有测试用例通过的同时改进代码。
  • 重构后所有测试用例必须仍然通过
  • 改进命名、提取函数、消除重复代码
  • 如果重构后任何测试用例失败,说明你的重构改变了代码行为 — 回退修改

Red Flags — If You Catch Yourself Thinking:

警示信号 — 如果你有以下想法:

ThoughtReality
"I'll write the implementation first, then add tests"That's not TDD. Write the test FIRST.
"This is too simple to test"If it's too simple to test, it's simple enough to test quickly.
"I'll write all the tests first, then implement"One test at a time. RED-GREEN-REFACTOR. One cycle.
"The test is basically the same as the implementation"Then you're testing implementation, not behavior. Rewrite the test.
想法实际情况
"我先实现功能,再添加测试用例"这不是TDD。先写测试用例。
"这个功能太简单了,没必要测试"如果简单到没必要测试,那也简单到可以快速完成测试。
"我先把所有测试用例写完,再进行实现"一次只写一个测试用例。遵循RED-GREEN-REFACTOR流程,完成一个周期再进行下一个。
"测试用例和实现代码基本一样"那你是在测试实现细节,而非行为。重写测试用例。

Rules

规则

  • ONE test at a time, ONE cycle at a time
  • NEVER skip RED — if the test doesn't fail first, it proves nothing
  • NEVER skip REFACTOR — clean code is part of the deliverable
  • Commit after each GREEN (passing test + minimal implementation)
  • 一次只写一个测试用例,一次只完成一个流程周期
  • 绝不能跳过RED阶段 — 如果测试用例一开始没有失败,那它毫无意义
  • 绝不能跳过REFACTOR阶段 — 整洁的代码是交付成果的一部分
  • 每次完成GREEN阶段(测试通过+最小化实现)后提交代码