testing-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Testing Patterns

测试模式

Principles for reliable test suites.

构建可靠测试套件的原则。

1. Testing Pyramid

1. 测试金字塔

        /\          E2E (Few)
       /  \         Critical flows
      /----\
     /      \       Integration (Some)
    /--------\      API, DB queries
   /          \
  /------------\    Unit (Many)
                    Functions, classes

        /\          E2E(少量)
       /  \         关键流程
      /----\
     /      \       集成测试(适量)
    /--------\      API、数据库查询
   /          \
  /------------\    单元测试(大量)
                    函数、类

2. AAA Pattern

2. AAA 模式

StepPurpose
ArrangeSet up test data
ActExecute code under test
AssertVerify outcome

步骤目的
Arrange设置测试数据
Act执行待测试代码
Assert验证结果

3. Test Type Selection

3. 测试类型选择

When to Use Each

适用场景

TypeBest ForSpeed
UnitPure functions, logicFast (<50ms)
IntegrationAPI, DB, servicesMedium
E2ECritical user flowsSlow

类型最佳适用场景速度
Unit(单元测试)纯函数、业务逻辑快(<50ms)
Integration(集成测试)API、数据库、服务中等
E2E关键用户流程

4. Unit Test Principles

4. 单元测试原则

Good Unit Tests

优质单元测试的特征

PrincipleMeaning
Fast< 100ms each
IsolatedNo external deps
RepeatableSame result always
Self-checkingNo manual verification
TimelyWritten with code
原则含义
快速每个测试<100ms
隔离无外部依赖
可重复结果始终一致
自校验无需人工验证
及时与代码同步编写

What to Unit Test

单元测试的测试范围

TestDon't Test
Business logicFramework code
Edge casesThird-party libs
Error handlingSimple getters

需测试无需测试
业务逻辑框架代码
边缘情况第三方库
错误处理简单的 getter 方法

5. Integration Test Principles

5. 集成测试原则

What to Test

测试范围

AreaFocus
API endpointsRequest/response
DatabaseQueries, transactions
External servicesContracts
领域重点
API 端点请求/响应
数据库查询、事务
外部服务契约

Setup/Teardown

前置/后置处理

PhaseAction
Before AllConnect resources
Before EachReset state
After EachClean up
After AllDisconnect

阶段操作
Before All连接资源
Before Each重置状态
After Each清理资源
After All断开连接

6. Mocking Principles

6. 模拟(Mocking)原则

When to Mock

何时使用模拟

MockDon't Mock
External APIsThe code under test
Database (unit)Simple dependencies
Time/randomPure functions
NetworkIn-memory stores
需模拟无需模拟
外部 API待测试代码
数据库(单元测试中)简单依赖
时间/随机函数纯函数
网络请求内存存储

Mock Types

模拟类型

TypeUse
StubReturn fixed values
SpyTrack calls
MockSet expectations
FakeSimplified implementation

类型用途
Stub返回固定值
Spy跟踪调用情况
Mock设置预期结果
Fake简化实现

7. Test Organization

7. 测试组织

Naming

命名规范

PatternExample
Should behavior"should return error when..."
When condition"when user not found..."
Given-when-then"given X, when Y, then Z"
模式示例
行为描述"should return error when..."(当...时应返回错误)
条件描述"when user not found..."(当用户未找到时...)
Given-when-then"given X, when Y, then Z"(给定X,当执行Y时,结果为Z)

Grouping

分组方式

LevelUse
describeGroup related tests
it/testIndividual case
beforeEachCommon setup

层级用途
describe分组相关测试
it/test单个测试用例
beforeEach公共前置设置

8. Test Data

8. 测试数据

Strategies

策略

ApproachUse
FactoriesGenerate test data
FixturesPredefined datasets
BuildersFluent object creation
方法用途
Factories生成测试数据
Fixtures预定义数据集
Builders流畅式对象创建

Principles

原则

  • Use realistic data
  • Randomize non-essential values (faker)
  • Share common fixtures
  • Keep data minimal

  • 使用真实感数据
  • 非关键值随机化(使用faker)
  • 共享通用测试数据
  • 保持数据精简

9. Best Practices

9. 最佳实践

PracticeWhy
One assert per testClear failure reason
Independent testsNo order dependency
Fast testsRun frequently
Descriptive namesSelf-documenting
Clean upAvoid side effects

实践原因
每个测试一个断言明确失败原因
测试独立无依赖无执行顺序依赖
测试执行快速可频繁运行
命名具有描述性自文档化
清理资源避免副作用

10. Anti-Patterns

10. 反模式

❌ Don't✅ Do
Test implementationTest behavior
Duplicate test codeUse factories
Complex test setupSimplify or split
Ignore flaky testsFix root cause
Skip cleanupReset state

Remember: Tests are documentation. If someone can't understand what the code does from the tests, rewrite them.
❌ 不要做✅ 应该做
测试实现细节测试行为
重复测试代码使用工厂方法
复杂的测试前置设置简化或拆分
忽略不稳定测试修复根本原因
跳过资源清理重置状态

注意: 测试即文档。如果有人无法通过测试理解代码功能,请重写测试。