test-driven-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTest-Driven Development (TDD)
测试驱动开发(TDD)
Red → Green → Refactor cycle for all code changes.
所有代码变更遵循 Red → Green → Refactor 循环。
The TDD Cycle
TDD 循环
- RED: Write failing test
- GREEN: Write minimal code to pass
- REFACTOR: Improve code quality
- RED(红):编写失败的测试用例
- GREEN(绿):编写最少的代码让测试通过
- REFACTOR(重构):提升代码质量
Repeat for each requirement
针对每个需求重复上述步骤
When to Apply TDD
何时应用TDD
✅ Always use TDD for:
- New functions/methods
- New features
- Bug fixes (reproduce first)
- Refactoring existing code
- API changes
❌ Skip TDD for:
- UI styling tweaks
- Configuration changes
- Documentation updates
✅ 以下场景必须使用TDD:
- 新函数/方法
- 新功能
- Bug修复(先复现问题)
- 现有代码重构
- API变更
❌ 以下场景可跳过TDD:
- UI样式微调
- 配置变更
- 文档更新
Process
流程
1. Write Failing Test First
1. 先编写失败的测试用例
elixir
undefinedelixir
undefinedStart with test
从测试开始
test "calculates total with tax" do
result = Calculator.calculate_total([100, 200])
assert Money.equal?(result, Money.new(:USD, 324))
end
test "calculates total with tax" do
result = Calculator.calculate_total([100, 200])
assert Money.equal?(result, Money.new(:USD, 324))
end
Run test - should FAIL
运行测试 - 应该失败
mix test
undefinedmix test
undefined2. Implement Minimal Code
2. 编写最简实现代码
elixir
undefinedelixir
undefinedJust enough to pass
仅编写足够让测试通过的代码
def calculate_total(prices) do
prices |> Enum.sum() |> Kernel.*(1.08) |> Money.new(:USD)
end
undefineddef calculate_total(prices) do
prices |> Enum.sum() |> Kernel.*(1.08) |> Money.new(:USD)
end
undefined3. Refactor
3. 重构
Extract constants, improve naming, etc.
提取常量、优化命名等。
Test Patterns by Stack
各技术栈的测试模式
Backend (Elixir)
后端(Elixir)
- File:
test/path/module_test.exs - Pattern:
apps/api/test/your_app/task/task_test.exs
- 文件路径:
test/path/module_test.exs - 示例:
apps/api/test/your_app/task/task_test.exs
Frontend (TypeScript)
前端(TypeScript)
- File:
ComponentName.test.tsx - Pattern:
mobile/libraries/atorasu/atoms/Button/Button.test.tsx
- 文件路径:
ComponentName.test.tsx - 示例:
mobile/libraries/atorasu/atoms/Button/Button.test.tsx
Critical Rules
核心规则
- Tests MUST fail first (verify test works)
- One test per requirement
- Test behavior, not implementation
- Run FULL test suite before commit
- NEVER skip failing tests
- 测试必须先失败(验证测试用例有效)
- 每个需求对应一个测试用例
- 测试行为,而非实现细节
- 提交前运行完整测试套件
- 绝不跳过失败的测试用例
Common Pitfalls
常见误区
- Writing implementation before test
- Tests that pass without implementation (false positive)
- Testing implementation details instead of behavior
- Not running test to verify it fails first
- 先编写实现代码再写测试
- 未实现代码测试却通过(假阳性)
- 测试实现细节而非行为
- 未运行测试验证其初始为失败状态
Verification
验证方式
bash
undefinedbash
undefinedBackend
后端
mix test path/to/test.exs
mix test path/to/test.exs
Frontend
前端
yarn test path/to/test.tsx
undefinedyarn test path/to/test.tsx
undefined