Skip to content

测试-Driven Development

Red-Green-Refactor cycle: 编写 failing 测试, 制作它 通过, 然后 clean 上.

你将学到

  • three phases 的 TDD cycle: Red, Green, Refactor
  • 为什么编写测试首先 shapes better 设计
  • Keeping 测试 and code in tiny, reversible steps
  • 常见 obstacles and 如何 overcome 它们

概念讲解

Red, Green, Refactor

Test-Driven Development (TDD) is a discipline where you write the test before the production code. The cycle has three phases. Red: write a small test for the next bit of behavior and watch it fail (the code does not exist yet). Green: write the simplest code that makes the test pass — no more. Refactor: improve the code's structure without changing behavior, with the test as a safety net. Repeat.

Why Test First

Writing the test first forces you to think about the interface and the desired behavior before getting lost in implementation. It keeps every piece of code born with a test, so coverage is organic rather than retrofitted. It also gives instant feedback: you know the test can fail (you saw it red), so it is not a tautology that always passes. And it tends to produce code that is testable by construction, with dependencies injected and side effects isolated.

Tiny Steps

The power of TDD comes from tiny, reversible steps. A cycle might take two minutes: one test, one function, one refactor. Small steps mean you almost never debug, because the last change is small and obvious when something breaks. If you write a hundred lines before testing, a failure could be anywhere; with TDD, it is almost always the line you just wrote.

Obstacles

TDD is hard to apply to UI exploration, throwaway prototypes, or when you do not yet know the design. In those cases, write a spike (throwaway code to learn the problem), then delete it and TDD the real version. TDD also feels slow at first; with practice the cycle becomes second-nature and overall speed increases because you spend far less time debugging.

In Practice

Start TDD on a pure function with clear inputs and outputs — a calculator, a validator, a formatter. Write one test for the simplest case, watch it fail, write the minimum code to pass, and refactor. Then add the next case (an edge, an error) and repeat. The cycle should take one to three minutes; if it takes longer, your step is too big and you should split it. When a test fails unexpectedly, you almost never need to debug — the failure is in the last line you wrote. Commit after each green cycle so your history is a sequence of small, working steps. Over a few weeks the discipline becomes habit, and you will find yourself writing better-designed code because testability forces you to inject dependencies, isolate side effects, and keep functions small.

示例代码

              // RED — write the test first (it fails: fizzBuzz does not exist)
import { describe, it, expect } from "vitest";
import { fizzBuzz } from "./fizzBuzz";

describe("fizzBuzz", () => {
  it("returns Fizz for multiples of 3", () => {
    expect(fizzBuzz(3)).toBe("Fizz");
  });
});

// GREEN — write the minimum code to pass
export function fizzBuzz(n: number): string {
  if (n % 3 === 0) return "Fizz";
  return String(n);
}

// REFACTOR — now add the next test for 5, then 15, generalizing
// the code step by step. Each cycle stays green.
            

开始使用 one failing 测试 for simplest 情况. 制作它 通过使用最少 code 可能. 仅然后添加下一个情况 and generalize. cycle keeps 设计 clean and bugs 局部.

动手试一试

  • Code Diff

    Review 每个 Red-Green-Refactor diff 之前 committing.

  • JSON Formatter

    Inspect structured 输出你的测试 assert 针对.

常见错误

错误写法

Skipping Red phase and 编写测试 + code together

正确做法

总是运行测试 and see 它失败首先. 如果它 通过 immediately, 测试是 错误 or 测试错误 thing.

错误写法

编写更多 than 最小值 code in Green

正确做法

Green 是 for 制作测试通过, 无更多. 保存 generalization and cleanup for Refactor phase 所以每个步骤是 verifiable.

练习 测试-Driven Development

4 个练习

练习 测试-Driven Development

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

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

查看错误