testing-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTesting Best Practices
测试最佳实践
Unit testing, integration testing, and TDD principles for reliable, maintainable test suites. Guidelines for writing effective tests that provide confidence and documentation.
本文介绍用于构建可靠、可维护测试套件的单元测试、集成测试以及TDD原则,提供编写能带来信心且兼具文档作用的高效测试的指导方针。
When to Apply
适用场景
Reference these guidelines when:
- Writing unit tests
- Writing integration tests
- Reviewing test code
- Improving test coverage
- Setting up testing strategy
在以下场景中可参考本指南:
- 编写单元测试
- 编写集成测试
- 评审测试代码
- 提升测试覆盖率
- 制定测试策略
Rule Categories by Priority
按优先级划分的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Test Structure | CRITICAL | |
| 2 | Test Isolation | CRITICAL | |
| 3 | Assertions | HIGH | |
| 4 | Test Data | HIGH | |
| 5 | Mocking | MEDIUM | |
| 6 | Coverage | MEDIUM | |
| 7 | Performance | LOW | |
| 优先级 | 类别 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | 测试结构 | 关键 | |
| 2 | 测试隔离 | 关键 | |
| 3 | 断言 | 高 | |
| 4 | 测试数据 | 高 | |
| 5 | 模拟(Mocking) | 中 | |
| 6 | 覆盖率 | 中 | |
| 7 | 性能 | 低 | |
Quick Reference
快速参考
1. Test Structure (CRITICAL)
1. 测试结构(关键)
- - Arrange, Act, Assert pattern
struct-aaa - - Descriptive test names
struct-naming - - One logical assertion per test
struct-one-assert - - Organized test suites
struct-describe-it - - BDD style when appropriate
struct-given-when-then
- - 准备、执行、断言(Arrange, Act, Assert)模式
struct-aaa - - 描述性测试名称
struct-naming - - 每个测试仅包含一个逻辑断言
struct-one-assert - - 结构化的测试套件
struct-describe-it - - 适当时使用BDD风格
struct-given-when-then
2. Test Isolation (CRITICAL)
2. 测试隔离(关键)
- - Tests run independently
iso-independent - - No shared mutable state
iso-no-shared-state - - Same result every run
iso-deterministic - - Run in any order
iso-no-order-dependency - - Clean up after tests
iso-cleanup
- - 测试可独立运行
iso-independent - - 无共享可变状态
iso-no-shared-state - - 每次运行结果一致
iso-deterministic - - 可按任意顺序运行
iso-no-order-dependency - - 测试后清理环境
iso-cleanup
3. Assertions (HIGH)
3. 断言(高)
- - Specific assertions
assert-specific - - Helpful failure messages
assert-meaningful-messages - - Expected value first
assert-expected-first - - Use named constants
assert-no-magic-numbers
- - 具体的断言
assert-specific - - 有帮助的失败提示信息
assert-meaningful-messages - - 预期值在前
assert-expected-first - - 使用命名常量
assert-no-magic-numbers
4. Test Data (HIGH)
4. 测试数据(高)
- - Use factories/builders
data-factories - - Minimal test data
data-minimal - - Realistic edge cases
data-realistic - - Manage test fixtures
data-fixtures
- - 使用工厂/构建器模式
data-factories - - 最小化测试数据
data-minimal - - 贴合实际的边界用例
data-realistic - - 管理测试固定数据
data-fixtures
5. Mocking (MEDIUM)
5. 模拟(Mocking)(中)
- - Mock at boundaries
mock-only-boundaries - - Verify important calls
mock-verify-interactions - - Don't over-mock
mock-minimal - - Realistic mock behavior
mock-realistic
- - 仅在边界处使用模拟
mock-only-boundaries - - 验证重要调用
mock-verify-interactions - - 避免过度模拟
mock-minimal - - 模拟行为贴合实际
mock-realistic
6. Coverage (MEDIUM)
6. 覆盖率(中)
- - Focus on meaningful coverage
cov-meaningful - - Cover edge cases
cov-edge-cases - - Test error scenarios
cov-unhappy-paths - - 100% isn't the goal
cov-not-100-percent
- - 聚焦有意义的覆盖率
cov-meaningful - - 覆盖边界用例
cov-edge-cases - - 测试错误场景
cov-unhappy-paths - - 100%覆盖率并非目标
cov-not-100-percent
7. Performance (LOW)
7. 性能(低)
- - Unit tests run fast
perf-fast-unit - - Integration tests can be slower
perf-slow-integration - - Run tests in parallel
perf-parallel
- - 单元测试需快速运行
perf-fast-unit - - 集成测试可允许较慢速度
perf-slow-integration - - 并行运行测试
perf-parallel
Essential Guidelines
核心指导方针
For detailed examples, see the rule files in the directory.
rules/如需详细示例,请查看目录下的规则文件。
rules/AAA Pattern (Arrange, Act, Assert)
AAA模式(Arrange, Act, Assert)
typescript
it('calculates total with discount', () => {
// Arrange - set up test data
const cart = new ShoppingCart();
cart.addItem({ name: 'Book', price: 20 });
cart.applyDiscount(0.1);
// Act - execute the code under test
const total = cart.getTotal();
// Assert - verify the result
expect(total).toBe(18);
});typescript
it('calculates total with discount', () => {
// Arrange - set up test data
const cart = new ShoppingCart();
cart.addItem({ name: 'Book', price: 20 });
cart.applyDiscount(0.1);
// Act - execute the code under test
const total = cart.getTotal();
// Assert - verify the result
expect(total).toBe(18);
});Descriptive Test Names
描述性测试名称
typescript
// ✅ Describes behavior and scenario
describe('UserService.register', () => {
it('creates user with hashed password', () => {});
it('throws ValidationError when email is invalid', () => {});
it('sends welcome email after successful registration', () => {});
});
// ❌ Vague names
it('test1', () => {});
it('should work', () => {});typescript
// ✅ Describes behavior and scenario
describe('UserService.register', () => {
it('creates user with hashed password', () => {});
it('throws ValidationError when email is invalid', () => {});
it('sends welcome email after successful registration', () => {});
});
// ❌ Vague names
it('test1', () => {});
it('should work', () => {});Test Isolation
测试隔离
typescript
// ✅ Each test sets up its own data
beforeEach(() => {
mockRepository = { save: jest.fn(), find: jest.fn() };
service = new OrderService(mockRepository);
});
// ❌ Shared state between tests
let globalOrder: Order; // Tests depend on each othertypescript
// ✅ Each test sets up its own data
beforeEach(() => {
mockRepository = { save: jest.fn(), find: jest.fn() };
service = new OrderService(mockRepository);
});
// ❌ Shared state between tests
let globalOrder: Order; // Tests depend on each otherTest Pyramid
测试金字塔
/\
/ \ E2E Tests (few)
/----\ - Test critical user flows
/ \ - Slow, expensive
/--------\ Integration Tests (some)
/ \ - Test component interactions
/------------\ - Database, API calls
/ \ Unit Tests (many)
/----------------\ - Fast, isolated
- Test single units /\
/ \ E2E Tests (few)
/----\ - Test critical user flows
/ \ - Slow, expensive
/--------\ Integration Tests (some)
/ \ - Test component interactions
/------------\ - Database, API calls
/ \ Unit Tests (many)
/----------------\ - Fast, isolated
- Test single unitsOutput Format
输出格式
When reviewing tests, output findings:
file:line - [category] Description of issueExample:
tests/user.test.ts:15 - [struct] Missing Arrange/Act/Assert separation
tests/order.test.ts:42 - [iso] Test depends on previous test's state
tests/cart.test.ts:28 - [assert] Multiple unrelated assertions in one test评审测试时,请按以下格式输出发现的问题:
file:line - [category] Description of issue示例:
tests/user.test.ts:15 - [struct] Missing Arrange/Act/Assert separation
tests/order.test.ts:42 - [iso] Test depends on previous test's state
tests/cart.test.ts:28 - [assert] Multiple unrelated assertions in one testHow to Use
使用方法
Read individual rule files for detailed explanations:
rules/struct-aaa-pattern.md
rules/iso-independent-tests.md
rules/data-factories.md阅读单个规则文件获取详细说明:
rules/struct-aaa-pattern.md
rules/iso-independent-tests.md
rules/data-factories.mdReferences
参考资料
This skill is built on testing best practices from:
- Jest: https://jestjs.io
- Vitest: https://vitest.dev
- Testing Library: https://testing-library.com
- Kent C. Dodds' testing principles
- TDD by Kent Beck
- Working Effectively with Legacy Code by Michael Feathers
本技能基于以下来源的测试最佳实践构建:
- Jest: https://jestjs.io
- Vitest: https://vitest.dev
- Testing Library: https://testing-library.com
- Kent C. Dodds的测试原则
- Kent Beck提出的TDD
- Michael Feathers所著《Working Effectively with Legacy Code》
Metadata
元数据
- Version: 1.0.0
- Rule Count: 23 rules across 7 categories
- License: MIT
- Last Updated: 2026-01-17
- 版本: 1.0.0
- 规则数量: 7个类别下共23条规则
- 许可证: MIT
- 最后更新日期: 2026-01-17
Contributing
贡献说明
These rules are derived from industry best practices and testing community standards. For detailed examples and additional context, refer to the individual rule files in the directory.
rules/这些规则源自行业最佳实践和测试社区标准。如需详细示例及更多背景信息,请参考目录下的单个规则文件。
rules/