testing-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Testing 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

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Test StructureCRITICAL
struct-
2Test IsolationCRITICAL
iso-
3AssertionsHIGH
assert-
4Test DataHIGH
data-
5MockingMEDIUM
mock-
6CoverageMEDIUM
cov-
7PerformanceLOW
perf-
优先级类别影响程度前缀
1测试结构关键
struct-
2测试隔离关键
iso-
3断言
assert-
4测试数据
data-
5模拟(Mocking)
mock-
6覆盖率
cov-
7性能
perf-

Quick Reference

快速参考

1. Test Structure (CRITICAL)

1. 测试结构(关键)

  • struct-aaa
    - Arrange, Act, Assert pattern
  • struct-naming
    - Descriptive test names
  • struct-one-assert
    - One logical assertion per test
  • struct-describe-it
    - Organized test suites
  • struct-given-when-then
    - BDD style when appropriate
  • struct-aaa
    - 准备、执行、断言(Arrange, Act, Assert)模式
  • struct-naming
    - 描述性测试名称
  • struct-one-assert
    - 每个测试仅包含一个逻辑断言
  • struct-describe-it
    - 结构化的测试套件
  • struct-given-when-then
    - 适当时使用BDD风格

2. Test Isolation (CRITICAL)

2. 测试隔离(关键)

  • iso-independent
    - Tests run independently
  • iso-no-shared-state
    - No shared mutable state
  • iso-deterministic
    - Same result every run
  • iso-no-order-dependency
    - Run in any order
  • iso-cleanup
    - Clean up after tests
  • iso-independent
    - 测试可独立运行
  • iso-no-shared-state
    - 无共享可变状态
  • iso-deterministic
    - 每次运行结果一致
  • iso-no-order-dependency
    - 可按任意顺序运行
  • iso-cleanup
    - 测试后清理环境

3. Assertions (HIGH)

3. 断言(高)

  • assert-specific
    - Specific assertions
  • assert-meaningful-messages
    - Helpful failure messages
  • assert-expected-first
    - Expected value first
  • assert-no-magic-numbers
    - Use named constants
  • assert-specific
    - 具体的断言
  • assert-meaningful-messages
    - 有帮助的失败提示信息
  • assert-expected-first
    - 预期值在前
  • assert-no-magic-numbers
    - 使用命名常量

4. Test Data (HIGH)

4. 测试数据(高)

  • data-factories
    - Use factories/builders
  • data-minimal
    - Minimal test data
  • data-realistic
    - Realistic edge cases
  • data-fixtures
    - Manage test fixtures
  • data-factories
    - 使用工厂/构建器模式
  • data-minimal
    - 最小化测试数据
  • data-realistic
    - 贴合实际的边界用例
  • data-fixtures
    - 管理测试固定数据

5. Mocking (MEDIUM)

5. 模拟(Mocking)(中)

  • mock-only-boundaries
    - Mock at boundaries
  • mock-verify-interactions
    - Verify important calls
  • mock-minimal
    - Don't over-mock
  • mock-realistic
    - Realistic mock behavior
  • mock-only-boundaries
    - 仅在边界处使用模拟
  • mock-verify-interactions
    - 验证重要调用
  • mock-minimal
    - 避免过度模拟
  • mock-realistic
    - 模拟行为贴合实际

6. Coverage (MEDIUM)

6. 覆盖率(中)

  • cov-meaningful
    - Focus on meaningful coverage
  • cov-edge-cases
    - Cover edge cases
  • cov-unhappy-paths
    - Test error scenarios
  • cov-not-100-percent
    - 100% isn't the goal
  • cov-meaningful
    - 聚焦有意义的覆盖率
  • cov-edge-cases
    - 覆盖边界用例
  • cov-unhappy-paths
    - 测试错误场景
  • cov-not-100-percent
    - 100%覆盖率并非目标

7. Performance (LOW)

7. 性能(低)

  • perf-fast-unit
    - Unit tests run fast
  • perf-slow-integration
    - Integration tests can be slower
  • perf-parallel
    - Run tests in parallel
  • perf-fast-unit
    - 单元测试需快速运行
  • perf-slow-integration
    - 集成测试可允许较慢速度
  • perf-parallel
    - 并行运行测试

Essential Guidelines

核心指导方针

For detailed examples, see the rule files in the
rules/
directory.
如需详细示例,请查看
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 other
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 other

Test 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 units

Output Format

输出格式

When reviewing tests, output findings:
file:line - [category] Description of issue
Example:
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 test

How 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.md

References

参考资料

This skill is built on testing best practices from:
本技能基于以下来源的测试最佳实践构建:

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
rules/
directory.
这些规则源自行业最佳实践和测试社区标准。如需详细示例及更多背景信息,请参考
rules/
目录下的单个规则文件。