Skip to content

测试-Driven Development (TDD)

一句话解释

TDD 平均值编写测试首先, watching 它失败 (red), 编写 code 到通过它 (green), 然后 improving code (refactor).

用大白话说

TDD flips normal workflow. 相反的 编写 code and 然后测试它, 你编写测试首先. 这个 sounds 向后, 但它's powerful.

The cycle 有 three steps:

  1. Red: 编写测试 for behavior 你想要. 运行它 — 它失败因为 code doesn't exist yet.
  2. Green: 编写 simplest code 那个制作测试通过. Don't over-engineer.
  3. Refactor: Improve code's 结构 and readability. 测试 protect 你 — 如果你 break 某事, 测试失败.

Writing 测试首先 forces 你到 think 关于接口 and behavior 之前 implementation. 这个 leads 到 better-设计, 更多 testable code. 你也 获取 immediate feedback and growing suite 的测试那个 document expected behavior.

示例

javascript
// RED: Write failing test
test('fizzbuzz returns Fizz for 3', () => {
  expect(fizzbuzz(3)).toBe('Fizz');
});
// Run: fails (fizzbuzz doesn't exist)

// GREEN: Write minimal code
function fizzbuzz(n) {
  if (n % 3 === 0) return 'Fizz';
  return String(n);
}
// Run: passes

// REFACTOR: improve if needed

TDD cycle: 编写 failing 测试, implement minimally, 然后 refactor.

常见混淆

  • 容易混淆的对象: BDD

    关键区别: TDD 是 coding 练习 (测试-首先); BDD focuses on 描述 behavior in natural language for 所有 stakeholders.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表