Skip to content

Test-Driven Development

测试类

Use before implementing any feature or fixing a bug, before writing implementation code.

Quick Start

Understand in 30 Seconds

Write test first. Watch it fail. Write minimal code to pass.

Core Principle: If you haven't seen the test fail, you don't know it tests the right thing.

When to Use

  • New features
  • Bug fixes
  • Refactoring
  • Behavior changes

Complete Guide

Iron Law

No production code without a failing test first

RED-GREEN-REFACTOR Cycle

RED - Write Failing Test

  • One behavior
  • Clear name
  • Real code

Verify RED - Watch It Fail

Must execute. Never skip.

GREEN - Minimal Coding

Write the simplest code to pass the test.

Verify GREEN - Watch It Pass

Must execute.

REFACTOR - Cleanup

Only after GREEN: eliminate duplication, improve naming, extract helpers

Red Flags

  • Writing code before tests
  • Writing tests after implementation
  • Tests pass immediately
  • Cannot explain why test fails

All of these mean: Delete the code. Start over with TDD.

Prerequisite Skills

Follow-up Skills