AgentSkillsCN

practicing-tdd

测试驱动开发的工作流程原则与“红-绿-重构”循环。当您采用先写测试、再实现功能或修复缺陷、或以测试优先的方式实现复杂逻辑时,可选用此方案。

SKILL.md
--- frontmatter
name: practicing-tdd
description: Test-Driven Development workflow principles and RED-GREEN-REFACTOR cycle. Use when writing new features, fixing bugs, or implementing complex logic with a test-first approach.

Practicing TDD

Write tests first, code second.


1. The TDD Flow and Cycle

  1. Write a list of the test scenarios you want to cover
  2. 🔴 [RED] Write failing test: Turn exactly one item on the list into an actual, concrete, runnable test
  3. 🟢 [GREEN] Write minimal code to pass: Change the code to make the test (& all previous tests) pass (adding items to the list as you discover them)
  4. 🔵 [REFACTOR] Improve code quality: Optionally refactor to improve the implementation design
  5. Until the list is empty, go back to #2

2. The Three Laws of TDD

  1. Write production code only to make a failing test pass
  2. Write only enough test to demonstrate failure
  3. Write only enough code to make the test pass

3. RED Phase Principles

What to Write

FocusExample
Behavior"should add two numbers"
Edge cases"should handle empty input"
Error states"should throw for invalid data"

RED Phase Rules

  • Test must fail first
  • Test name describes expected behavior
  • One assertion per test (ideally)

4. GREEN Phase Principles

Minimum Code

PrincipleMeaning
YAGNIYou Aren't Gonna Need It
Simplest thingWrite the minimum to pass
No optimizationJust make it work

GREEN Phase Rules

  • Don't write unneeded code
  • Don't optimize yet
  • Pass the test, nothing more

5. REFACTOR Phase Principles

What to Improve

AreaAction
DuplicationExtract common code
NamingMake intent clear
StructureImprove organization
ComplexitySimplify logic

REFACTOR Rules

  • All tests must stay green
  • Small incremental changes
  • Commit after each refactor

6. AAA Pattern

Every test follows:

StepPurpose
ArrangeSet up test data
ActExecute code under test
AssertVerify expected outcome

7. When to Use TDD

ScenarioTDD Value
New featureHigh
Bug fixHigh (write test first)
Complex logicHigh
ExploratoryLow (spike, then TDD)
UI layoutLow

8. Test Prioritization

PriorityTest Type
1Happy path
2Error cases
3Edge cases
4Performance

9. Anti-Patterns

❌ Don't✅ Do
Skip the RED phaseWatch test fail first
Write tests afterWrite tests before
Over-engineer initialKeep it simple
Multiple assertsOne behavior per test
Test implementationTest behavior

10. AI-Augmented TDD

Multi-Agent Pattern

AgentRole
Agent AWrite failing tests (RED)
Agent BImplement to pass (GREEN)
Agent COptimize (REFACTOR)

Remember: The test is the specification. If you can't write a test, you don't understand the requirement.