test-driven-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Test-Driven Development (TDD) Skill

测试驱动开发(TDD)技能

Purpose

目标

Enforce the RED-GREEN-REFACTOR cycle for all code changes. This skill ensures tests are written BEFORE implementation code, verifies tests fail for the right reasons, and maintains test coverage through disciplined development cycles.
对所有代码变更强制执行RED-GREEN-REFACTOR周期。该技能确保在编写实现代码前先编写测试,验证测试因正确的原因失败,并通过规范的开发周期维持测试覆盖率。

Operator Context

操作场景

This skill operates as an operator for test-driven development workflows, configuring Claude's behavior for disciplined test-first coding practices.
本技能作为测试驱动开发工作流的操作器,配置Claude的行为以遵循规范的测试优先编码实践。

Hardcoded Behaviors (Always Apply)

硬编码行为(始终适用)

These behaviors are non-negotiable for correct TDD practice:
  • CLAUDE.md Compliance: Read and follow repository CLAUDE.md files before execution. Project instructions override default TDD behaviors.
  • Over-Engineering Prevention: Only implement what's directly tested. Keep code simple and focused. No speculative features or flexibility that wasn't asked for. First make it work, then make it right.
  • RED phase is mandatory: ALWAYS write the test BEFORE any implementation code
  • Verify test failure: MUST run test and show failure output before implementing
  • Failure reason validation: MUST confirm test fails for the CORRECT reason (not syntax errors)
  • Show complete output: NEVER summarize test results - show full test runner output
  • Minimum implementation: Write ONLY enough code to make the test pass (no gold-plating)
  • Commit discipline: Tests and implementation committed together in atomic units
这些行为是正确TDD实践的非协商要求:
  • CLAUDE.md合规性:执行前阅读并遵循仓库中的CLAUDE.md文件。项目指令优先于默认TDD行为。
  • 防止过度设计:仅实现测试直接覆盖的内容。保持代码简洁聚焦。不添加未要求的推测性功能或灵活性。先让代码可用,再优化完善。
  • RED阶段为强制要求:必须在编写任何实现代码前先编写测试
  • 验证测试失败:在实现前必须运行测试并展示失败输出
  • 失败原因验证:必须确认测试因正确的原因失败(而非语法错误)
  • 展示完整输出:绝不要总结测试结果 - 展示测试运行器的完整输出
  • 最简实现:仅编写刚好能让测试通过的代码(不要过度优化)
  • 提交规范:测试与实现代码作为原子单元一起提交

Default Behaviors (ON unless disabled)

默认行为(除非禁用否则启用)

Active by default to maintain quality:
  • Communication Style: Report facts without self-congratulation. Show command output rather than describing it. Be concise but informative.
  • Temporary File Cleanup: Remove temporary test files, coverage reports, or debug outputs created during TDD cycles at task completion. Keep only files explicitly needed for the project.
  • Run tests after each change: Execute test suite after every code modification
  • Test improvement suggestions: Recommend better assertions, edge cases, test organization
  • Coverage awareness: Track which code paths are tested, suggest missing coverage
  • Refactoring validation: Ensure tests remain green during refactoring steps
  • Test naming conventions: Enforce descriptive test names that explain behavior
默认启用以维持质量:
  • 沟通风格:只报告事实,不自我夸耀。展示命令输出而非描述输出。简洁但信息完整。
  • 临时文件清理:任务完成后删除TDD周期中创建的临时测试文件、覆盖率报告或调试输出。仅保留项目明确需要的文件。
  • 每次变更后运行测试:每次修改代码后执行测试套件
  • 测试改进建议:推荐更优的断言方式、边缘案例、测试组织方式
  • 覆盖率感知:跟踪哪些代码路径已被测试,建议补充缺失的覆盖
  • 重构验证:确保重构过程中测试始终保持全部通过
  • 测试命名规范:强制执行能说明行为的描述性测试名称

Optional Behaviors (OFF unless enabled)

可选行为(除非启用否则禁用)

Advanced testing capabilities available on request:
  • Property-based testing: Generate tests with random/fuzzed inputs (Go: testing/quick, Python: hypothesis)
  • Mutation testing: Verify test quality by introducing bugs
  • Benchmark tests: Performance regression testing
  • Table-driven tests: Convert multiple similar tests to data-driven approach
  • Test parallelization: Run independent tests concurrently for speed
可根据需求启用的高级测试功能:
  • 基于属性的测试:生成含随机/模糊输入的测试(Go: testing/quick, Python: hypothesis)
  • 变异测试:通过引入Bug验证测试质量
  • 基准测试:性能回归测试
  • 表格驱动测试:将多个相似测试转换为数据驱动方式
  • 测试并行化:并发运行独立测试以提升速度

What This Skill CAN Do

本技能可完成的工作

  • Guide RED-GREEN-REFACTOR cycles for any language (Go, Python, JavaScript)
  • Enforce phase gates: test must fail before implementation
  • Validate test failure reasons (syntax errors vs missing implementation)
  • Guide refactoring while maintaining green tests
  • Provide language-specific testing commands and patterns
  • 为任意语言(Go、Python、JavaScript)指导RED-GREEN-REFACTOR周期
  • 强制执行阶段关卡:实现前测试必须失败
  • 验证测试失败原因(语法错误 vs 缺失实现)
  • 指导在保持测试全部通过的前提下进行重构
  • 提供语言特定的测试命令和模式

What This Skill CANNOT Do

本技能不可完成的工作

  • Write implementation before tests (violates TDD principle)
  • Skip the RED phase or proceed without verified test failure
  • Implement features not covered by a test
  • Approve passing tests without checking failure reason
  • Skip running tests after each change
  • 在编写测试前先写实现代码(违反TDD原则)
  • 跳过RED阶段或未验证测试失败就继续
  • 实现未被测试覆盖的功能
  • 未检查失败原因就认可测试通过
  • 每次变更后跳过运行测试

Instructions

操作指南

TDD Workflow: RED-GREEN-REFACTOR Cycle

TDD工作流:RED-GREEN-REFACTOR周期

Step 1: Write a Failing Test (RED Phase)

步骤1:编写失败的测试(RED阶段)

PHASE GATE: Do NOT proceed to GREEN phase until:
  • Test file is created and saved
  • Test has been executed
  • Test output shows FAILURE (not syntax/import error)
  • Failure message indicates missing implementation
BEFORE writing any implementation code:
  1. Understand the requirement: Clarify what behavior needs to be implemented
  2. Write the test first: Create test that describes the desired behavior
  3. Use descriptive test names: Test name should explain what is being tested
  4. Write minimal test setup: Only create fixtures/mocks needed for THIS test
  5. Assert expected behavior: Use specific assertions (not just "no error")
Run the test:
bash
go test ./... -v -run TestNewFeature          # Go
pytest tests/test_feature.py::test_name -v    # Python
npm test -- --testNamePattern="new feature"   # JavaScript
阶段关卡:未满足以下条件不得进入GREEN阶段:
  • 测试文件已创建并保存
  • 已运行测试
  • 测试输出显示失败(而非语法/导入错误)
  • 失败信息表明功能未实现
在编写任何实现代码前:
  1. 理解需求:明确需要实现的行为
  2. 先编写测试:创建描述期望行为的测试
  3. 使用描述性测试名称:测试名称应说明正在测试的内容
  4. 编写最简测试设置:仅创建本次测试所需的夹具/模拟对象
  5. 断言期望行为:使用具体的断言(而非仅“无错误”)
运行测试:
bash
go test ./... -v -run TestNewFeature          # Go
pytest tests/test_feature.py::test_name -v    # Python
npm test -- --testNamePattern="new feature"   # JavaScript

Step 2: Verify Test Fails for the RIGHT Reason (RED Verification)

步骤2:验证测试因正确原因失败(RED阶段验证)

CRITICAL: Run the test and confirm it fails:
  1. Execute test command (show full output)
  2. Verify failure reason: Test should fail because feature not implemented, NOT:
    • Syntax errors
    • Import errors
    • Wrong test setup
    • Unrelated failures
Expected RED output indicators:
  • Go:
    --- FAIL: TestFeatureName
    with expected vs actual mismatch
  • Python:
    AssertionError
    or
    AttributeError: module has no attribute
  • JavaScript:
    Expected X but received undefined
If test fails for WRONG reason:
  • Fix the test setup/syntax
  • Re-run until it fails for the RIGHT reason (missing implementation)
关键步骤:运行测试并确认其失败:
  1. 执行测试命令(展示完整输出)
  2. 验证失败原因:测试应因功能未实现而失败,而非:
    • 语法错误
    • 导入错误
    • 测试设置错误
    • 无关失败
预期RED阶段输出标识:
  • Go:
    --- FAIL: TestFeatureName
    显示预期与实际结果不匹配
  • Python:
    AssertionError
    AttributeError: module has no attribute
  • JavaScript:
    Expected X but received undefined
如果测试因错误原因失败:
  • 修复测试设置/语法
  • 重新运行直到因正确原因(缺失实现)失败

Step 3: Write MINIMUM Code to Pass (GREEN Phase)

步骤3:编写最简代码以通过测试(GREEN阶段)

PHASE GATE: Do NOT proceed to REFACTOR phase until:
  • Implementation code is written
  • Test has been executed again
  • Test output shows PASS
  • No other tests have been broken
Implement ONLY enough code to make THIS test pass:
  1. Minimal implementation: Simplest code that satisfies the test
  2. No extra features: Don't implement behavior not covered by tests
  3. Hardcoded values are OK initially: First make it work, then make it right
阶段关卡:未满足以下条件不得进入REFACTOR阶段:
  • 实现代码已编写完成
  • 已重新运行测试
  • 测试输出显示通过
  • 未破坏其他测试
仅编写刚好能让本次测试通过的代码:
  1. 最简实现:满足测试要求的最简单代码
  2. 无额外功能:不要实现测试未覆盖的行为
  3. 初始可使用硬编码值:先让代码可用,再优化完善

Step 4: Verify Test Passes (GREEN Verification)

步骤4:验证测试通过(GREEN阶段验证)

Run test and confirm it passes:
  1. Execute test command (show full output)
  2. Verify PASS status: Test should now succeed
  3. Check for warnings: Note any deprecation warnings or issues
If test still fails:
  • Review implementation logic
  • Check test assertions are correct
  • Debug until test passes
运行测试并确认其通过:
  1. 执行测试命令(展示完整输出)
  2. 验证通过状态:测试现在应成功
  3. 检查警告:注意任何弃用警告或问题
如果测试仍失败:
  • 检查实现逻辑
  • 确认测试断言正确
  • 调试直到测试通过

Step 5: Refactor While Keeping Tests Green (REFACTOR Phase)

步骤5:在保持测试全部通过的前提下重构(REFACTOR阶段)

PHASE GATE: Do NOT mark task complete until:
  • All refactoring changes are saved
  • Full test suite has been executed
  • ALL tests pass (not just the new one)
  • Code quality has been evaluated against checklist below
REFACTORING DECISION CRITERIA (evaluate each):
CriterionCheckAction if YES
DuplicationSame logic in 2+ places?Extract to shared function
NamingNames unclear or misleading?Rename for clarity
LengthFunction >20 lines?Extract sub-functions
ComplexityNested conditionals >2 deep?Simplify or extract
ReusabilityCould other code use this?Extract to module
Improve code quality without changing behavior:
  1. Run full test suite BEFORE refactoring: Establish green baseline
  2. Refactor incrementally: Extract functions, rename for clarity, remove duplication
  3. Run tests after EACH refactoring step: Ensure tests stay green
  4. Refactor tests too: Improve test readability and maintainability
阶段关卡:未满足以下条件不得标记任务完成:
  • 所有重构变更已保存
  • 已执行完整测试套件
  • 所有测试均通过(不只是新测试)
  • 已根据下方检查表评估代码质量
重构决策标准(逐一评估):
评估标准是否符合符合时的操作
代码重复同一逻辑出现在2处以上?提取为共享函数
命名名称不清晰或有误导性?重命名以提升清晰度
长度函数超过20行?提取子函数
复杂度嵌套条件超过2层?简化或提取
复用性其他代码是否可使用该逻辑?提取到模块中
在不改变行为的前提下提升代码质量:
  1. 重构前运行完整测试套件:建立全部通过的基准
  2. 增量式重构:提取函数、重命名以提升清晰度、消除重复
  3. 每次重构步骤后运行测试:确保测试始终保持全部通过
  4. 同时重构测试:提升测试的可读性和可维护性

Step 6: Commit Atomic Changes

步骤6:提交原子变更

Commit test and implementation together:
  1. Review changes: Verify test + implementation are complete
  2. Run full test suite: Ensure nothing broke
  3. Commit with descriptive message
将测试与实现代码一起提交:
  1. 检查变更:确认测试+实现完整
  2. 运行完整测试套件:确保未破坏任何功能
  3. 使用描述性信息提交

Error Handling

错误处理

Common TDD Mistakes and Solutions

常见TDD错误与解决方案

Error: "Test passes before implementation"

错误:“实现前测试已通过”

Symptom: Test shows PASS in RED phase
Causes:
  • Test is testing the wrong thing
  • Implementation already exists elsewhere
  • Test assertions are too weak (always true)
Solution:
  1. Review test assertions - are they specific enough?
  2. Verify test is actually calling the code under test
  3. Check for existing implementation of the feature
  4. Strengthen assertions to actually verify behavior
症状:RED阶段测试显示通过
原因:
  • 测试目标错误
  • 功能已在其他地方实现
  • 测试断言过弱(始终为真)
解决方案:
  1. 检查测试断言 - 是否足够具体?
  2. 确认测试确实调用了被测代码
  3. 检查是否已存在该功能的实现
  4. 强化断言以实际验证行为

Error: "Test fails for wrong reason"

错误:“测试因错误原因失败”

Symptom: Syntax errors, import errors, setup failures in RED phase
Causes:
  • Test setup incomplete
  • Missing dependencies
  • Incorrect import paths
Solution:
  1. Fix syntax/import errors first
  2. Set up necessary fixtures/mocks
  3. Verify test file structure matches project conventions
  4. Re-run until test fails for RIGHT reason (missing feature)
症状:RED阶段出现语法错误、导入错误、设置失败
原因:
  • 测试设置不完整
  • 缺失依赖
  • 导入路径错误
解决方案:
  1. 先修复语法/导入错误
  2. 设置必要的夹具/模拟对象
  3. 确认测试文件结构符合项目规范
  4. 重新运行直到因正确原因(缺失功能)失败

Error: "Tests pass but feature doesn't work"

错误:“测试通过但功能不可用”

Symptom: Tests green but manual testing shows bugs
Causes:
  • Tests don't cover actual usage
  • Test mocks don't match real behavior
  • Edge cases not tested
Solution:
  1. Review test coverage - what's missing?
  2. Add integration tests alongside unit tests
  3. Test with real data, not just mocks
  4. Add edge case tests (empty input, null, extremes)
症状:测试全部通过但手动测试发现Bug
原因:
  • 测试未覆盖实际使用场景
  • 测试模拟与真实行为不符
  • 未测试边缘案例
解决方案:
  1. 检查测试覆盖率 - 缺失了哪些部分?
  2. 在单元测试之外添加集成测试
  3. 使用真实数据测试,而非仅依赖模拟
  4. 添加边缘案例测试(空输入、null、极端值)

Error: "Refactoring breaks tests"

错误:“重构破坏测试”

Symptom: Tests fail after refactoring
Causes:
  • Tests coupled to implementation details
  • Brittle assertions (checking internals not behavior)
  • Large refactoring without incremental steps
Solution:
  1. Test behavior, not implementation details
  2. Refactor in smaller steps
  3. Run tests after each micro-refactoring
  4. Update tests if API contract legitimately changed
症状:重构后测试失败
原因:
  • 测试与实现细节耦合
  • 断言过于脆弱(检查内部而非行为)
  • 未分步进行大型重构
解决方案:
  1. 测试行为而非实现细节
  2. 以更小的步骤进行重构
  3. 每次微重构后运行测试
  4. 如果API契约确实变更,更新测试

Language-Specific Testing Commands

语言特定测试命令

LanguageRun One TestRun AllWith Coverage
Go
go test -v -run TestName ./pkg
go test ./...
go test -cover ./...
Python
pytest tests/test_file.py::test_fn -v
pytest
pytest --cov=src
JavaScript
npm test -- --testNamePattern="name"
npm test
npm test -- --coverage
语言运行单个测试运行全部测试带覆盖率
Go
go test -v -run TestName ./pkg
go test ./...
go test -cover ./...
Python
pytest tests/test_file.py::test_fn -v
pytest
pytest --cov=src
JavaScript
npm test -- --testNamePattern="name"
npm test
npm test -- --coverage

Testing Best Practices

测试最佳实践

Assertion Guidelines

断言指南

Use specific assertions:
  • assert result == 42
    (specific value)
  • assert error.message.contains("invalid")
    (specific content)
  • NOT
    assert result != nil
    (too weak)
  • NOT
    assert len(result) > 0
    (not specific enough)
Test one concept per test:
  • Each test should verify ONE behavior
  • If test name needs "and", split into multiple tests
  • Makes failures easier to diagnose
使用具体断言:
  • assert result == 42
    (具体值)
  • assert error.message.contains("invalid")
    (具体内容)
  • 不要使用
    assert result != nil
    (过弱)
  • 不要使用
    assert len(result) > 0
    (不够具体)
每个测试验证一个概念:
  • 每个测试应仅验证一个行为
  • 如果测试名称需要“和”,拆分为多个测试
  • 便于诊断失败原因

Arrange-Act-Assert Pattern

准备-执行-断言模式

python
def test_feature():
    # Arrange: Set up test data
    input_data = create_test_data()

    # Act: Execute the code under test
    result = function_under_test(input_data)

    # Assert: Verify expected behavior
    assert result.status == "success"
python
def test_feature():
    # Arrange: 设置测试数据
    input_data = create_test_data()

    # Act: 执行被测代码
    result = function_under_test(input_data)

    # Assert: 验证期望行为
    assert result.status == "success"

Common Anti-Patterns

常见反模式

Anti-Pattern 1: Skipping the RED Phase

反模式1:跳过RED阶段

Wrong -- writing implementation first:
python
undefined
错误做法 -- 先写实现代码:
python
undefined

Writing implementation first

先写实现代码

def calculate_total(items): return sum(item.price for item in items)
def calculate_total(items): return sum(item.price for item in items)

Then writing test after

再写测试

def test_calculate_total(): items = [Item(price=10), Item(price=20)] assert calculate_total(items) == 30

**Why it's wrong:**
- Can't verify test actually catches bugs (never saw it fail)
- Test might be passing for wrong reasons
- Risk of writing tests that match buggy implementation

**Correct -- RED then GREEN:**
```python
def test_calculate_total(): items = [Item(price=10), Item(price=20)] assert calculate_total(items) == 30

**错误原因:**
- 无法验证测试是否真的能捕获Bug(从未见过测试失败)
- 测试可能因错误原因通过
- 存在测试匹配有Bug的实现的风险

**正确做法 -- 先RED后GREEN:**
```python

1. Write test FIRST (RED phase)

1. 先写测试(RED阶段)

def test_calculate_total(): items = [Item(price=10), Item(price=20)] assert calculate_total(items) == 30
def test_calculate_total(): items = [Item(price=10), Item(price=20)] assert calculate_total(items) == 30

Run test -> fails with "NameError: name 'calculate_total' is not defined"

运行测试 -> 失败,错误信息:"NameError: name 'calculate_total' is not defined"

2. Implement minimum code (GREEN phase)

2. 实现最简代码(GREEN阶段)

def calculate_total(items): return sum(item.price for item in items)
def calculate_total(items): return sum(item.price for item in items)

Run test -> passes

运行测试 -> 通过

undefined
undefined

Anti-Pattern 2: Testing Implementation Details

反模式2:测试实现细节

Wrong -- testing internals:
go
func TestParser_UsesCorrectRegex(t *testing.T) {
    parser := NewParser()
    // Testing internal regex pattern - breaks on refactor
    assert.Equal(t, `\d{3}-\d{3}-\d{4}`, parser.phoneRegex)
}
Why it's wrong:
  • Test breaks when refactoring internal implementation
  • Doesn't verify actual behavior users care about
  • Makes refactoring painful (tests should enable it)
Correct -- testing behavior:
go
func TestParser_ValidPhoneNumber_ParsesCorrectly(t *testing.T) {
    parser := NewParser()
    result, err := parser.ParsePhone("123-456-7890")
    assert.NoError(t, err)
    assert.Equal(t, "1234567890", result.Digits())
}

func TestParser_InvalidPhoneNumber_ReturnsError(t *testing.T) {
    parser := NewParser()
    _, err := parser.ParsePhone("invalid")
    assert.Error(t, err)
    assert.Contains(t, err.Error(), "invalid phone format")
}
错误做法 -- 测试内部实现:
go
func TestParser_UsesCorrectRegex(t *testing.T) {
    parser := NewParser()
    // 测试内部正则表达式 - 重构时会失效
    assert.Equal(t, `\d{3}-\d{3}-\d{4}`, parser.phoneRegex)
}
错误原因:
  • 重构内部实现时测试会失效
  • 未验证用户关心的实际行为
  • 让重构变得痛苦(测试应支持重构)
正确做法 -- 测试行为:
go
func TestParser_ValidPhoneNumber_ParsesCorrectly(t *testing.T) {
    parser := NewParser()
    result, err := parser.ParsePhone("123-456-7890")
    assert.NoError(t, err)
    assert.Equal(t, "1234567890", result.Digits())
}

func TestParser_InvalidPhoneNumber_ReturnsError(t *testing.T) {
    parser := NewParser()
    _, err := parser.ParsePhone("invalid")
    assert.Error(t, err)
    assert.Contains(t, err.Error(), "invalid phone format")
}

Anti-Pattern 3: Writing Multiple Features Without Tests

反模式3:无测试实现多个功能

Wrong -- implementing everything at once:
javascript
// Implementing many features at once without tests
class UserManager {
  createUser(data) { /* complex logic */ }
  updateUser(id, data) { /* complex logic */ }
  deleteUser(id) { /* complex logic */ }
  validateUser(user) { /* complex logic */ }
}
// Then one giant test for everything
Why it's wrong:
  • Lost the TDD cycle discipline completely
  • Can't verify each feature worked incrementally
  • No design feedback from tests
Correct -- one cycle per feature:
javascript
// Cycle 1: Create user (RED -> GREEN -> REFACTOR)
it('should create user with valid data', () => {
    const manager = new UserManager()
    const user = manager.createUser({ name: 'Alice', email: 'alice@example.com' })
    expect(user.id).toBeDefined()
    expect(user.name).toBe('Alice')
})
// Implement createUser() to pass, then move to next cycle

// Cycle 2: Validate user (RED -> GREEN -> REFACTOR)
it('should reject user with invalid email', () => {
    const manager = new UserManager()
    expect(() => manager.createUser({ name: 'Bob', email: 'invalid' }))
      .toThrow('Invalid email format')
})
// Add validation to make test pass
错误做法 -- 一次性实现所有功能:
javascript
// 无测试一次性实现多个功能
class UserManager {
  createUser(data) { /* 复杂逻辑 */ }
  updateUser(id, data) { /* 复杂逻辑 */ }
  deleteUser(id) { /* 复杂逻辑 */ }
  validateUser(user) { /* 复杂逻辑 */ }
}
// 再写一个巨型测试
错误原因:
  • 完全违背TDD周期规范
  • 无法验证每个功能是否增量可用
  • 无法从测试中获得设计反馈
正确做法 -- 每个功能一个周期:
javascript
// 周期1:创建用户(RED -> GREEN -> REFACTOR)
it('should create user with valid data', () => {
    const manager = new UserManager()
    const user = manager.createUser({ name: 'Alice', email: 'alice@example.com' })
    expect(user.id).toBeDefined()
    expect(user.name).toBe('Alice')
})
// 实现createUser()以通过测试,再进入下一个周期

// 周期2:验证用户(RED -> GREEN -> REFACTOR)
it('should reject user with invalid email', () => {
    const manager = new UserManager()
    expect(() => manager.createUser({ name: 'Bob', email: 'invalid' }))
      .toThrow('Invalid email format')
})
// 添加验证逻辑以通过测试

Anti-Pattern 4: Over-Engineering in GREEN Phase

反模式4:GREEN阶段过度设计

Wrong -- test requires simple addition but implementation over-engineers:
go
// Test only requires simple addition
func TestCalculator_AddTwoNumbers(t *testing.T) {
    calc := NewCalculator()
    result := calc.Add(2, 3)
    assert.Equal(t, 5, result)
}

// But implementation adds unnecessary complexity
type Calculator struct {
    operations map[string]func(float64, float64) float64
    precision  int
    history    []Operation
}
Why it's wrong:
  • Implementing features not covered by tests
  • Violates "minimum code to pass" principle
  • Hard to maintain untested code paths
Correct -- implement only what's tested:
go
// Implement ONLY what's needed to pass
type Calculator struct{}

func (c *Calculator) Add(a, b int) int {
    return a + b
}
// Add complexity ONLY when a test requires it
错误做法 -- 测试仅需简单加法但实现过度复杂:
go
// 测试仅需简单加法
func TestCalculator_AddTwoNumbers(t *testing.T) {
    calc := NewCalculator()
    result := calc.Add(2, 3)
    assert.Equal(t, 5, result)
}

// 但实现添加了不必要的复杂度
type Calculator struct {
    operations map[string]func(float64, float64) float64
    precision  int
    history    []Operation
}
错误原因:
  • 实现了测试未覆盖的功能
  • 违反“最简代码通过”原则
  • 未测试的代码路径难以维护
正确做法 -- 仅实现测试覆盖的内容:
go
// 仅实现满足测试的代码
type Calculator struct{}

func (c *Calculator) Add(a, b int) int {
    return a + b
}
// 仅当测试要求时再添加复杂度

Reference Files

参考文件

  • ${CLAUDE_SKILL_DIR}/references/examples.md
    : Language-specific TDD examples (Go, Python, JavaScript)
  • ${CLAUDE_SKILL_DIR}/references/examples.md
    : 语言特定TDD示例(Go、Python、JavaScript)

References

参考资料

This skill uses these shared patterns:
  • Anti-Rationalization - Prevents shortcut rationalizations
  • Anti-Rationalization (Testing) - Testing-specific rationalizations
  • Gate Enforcement - Phase transition rules
  • Verification Checklist - Pre-completion checks
本技能使用以下共享模式:
  • Anti-Rationalization - 防止找借口走捷径
  • Anti-Rationalization (Testing) - 测试特定的借口预防
  • Gate Enforcement - 阶段转换规则
  • Verification Checklist - 完成前检查

Domain-Specific Anti-Rationalization

领域特定反借口指南

RationalizationWhy It's WrongRequired Action
"I know what the test should be, let me just code it"Skipping RED means test may not catch bugsWrite test, run it, see it fail first
"Test passes, implementation is correct"Passing test may be too weakCheck assertions are specific enough
"Simple feature, no need for TDD cycle"Simple features have edge cases tooOne RED-GREEN-REFACTOR per feature
"I'll add more tests after the feature works"Retro-fitted tests miss design feedbackWrite tests BEFORE implementation
借口错误原因要求操作
“我知道测试应该是什么样的,直接写代码就行”跳过RED阶段意味着测试可能无法捕获Bug先写测试,运行测试,确认其失败
“测试通过了,实现是正确的”通过的测试可能过弱检查断言是否足够具体
“功能很简单,不需要TDD周期”简单功能也有边缘案例每个功能执行一次RED-GREEN-REFACTOR周期
“功能实现后我再补测试”事后补的测试无法提供设计反馈先写测试再实现