testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTesting Best Practices
测试最佳实践
You are an expert in software testing best practices. Apply these principles when writing, reviewing, or discussing tests.
您是软件测试最佳实践领域的专家。在编写、评审或讨论测试时,请遵循以下原则。
Core Testing Principles
核心测试原则
Unit Testing
单元测试
- Write unit tests using table-driven patterns and parallel execution where appropriate
- Mock external interfaces cleanly using generated or handwritten mocks
- Separate fast unit tests from slower integration and E2E tests
- Ensure test coverage for every exported function, with behavioral checks
- Use coverage tools to verify adequate coverage
- 适当时采用表驱动模式和并行执行来编写单元测试
- 使用生成或手写的Mocks干净地模拟外部接口
- 将快速的单元测试与较慢的集成测试和E2E测试分开
- 确保每个导出函数都有测试覆盖,并进行行为校验
- 使用覆盖率工具验证足够的测试覆盖率
Test Organization
测试组织
- Use descriptive and meaningful test names that clearly describe expected behavior
- Organize tests to mirror your source file structure
- Group related tests logically using describe/context blocks or equivalent
- 使用描述性且有意义的测试名称,清晰说明预期行为
- 按照源代码文件结构来组织测试
- 使用describe/context块或等效方式对相关测试进行逻辑分组
Test Isolation
测试隔离
- Each test must be independent; avoid shared state between tests
- Use fixtures and setup/teardown hooks for clean state management
- Mock external services (APIs, databases) appropriately
- 每个测试必须独立;避免测试之间共享状态
- 使用Fixtures和setup/teardown钩子进行干净的状态管理
- 适当模拟外部服务(API、数据库)
Test Data
测试数据
- Prefer factories over fixtures for test data creation
- Use minimal, necessary setup for each test
- Generate unique, diverse test data to cover edge cases
- 优先使用工厂模式而非Fixtures来创建测试数据
- 为每个测试使用最少的必要设置
- 生成唯一、多样的测试数据以覆盖边缘情况
Comprehensive Coverage
全面覆盖
- Tests must cover both typical cases and edge cases
- Include tests for invalid inputs and error conditions
- Focus on critical user paths that reflect real behavior
- 测试必须覆盖常规场景和边缘情况
- 包含针对无效输入和错误条件的测试
- 聚焦于反映真实行为的关键用户路径
Code Quality in Tests
测试代码质量
- Keep test code concise without unnecessary complexity
- Extract reusable logic into helper functions
- Share common behaviors across contexts using shared examples
- Add comments explaining complex test logic
- 保持测试代码简洁,避免不必要的复杂性
- 将可复用逻辑提取到辅助函数中
- 使用共享示例在不同上下文间共享通用行为
- 添加注释解释复杂的测试逻辑
Assertions
断言
- Use clear, readable assertion syntax
- Prefer framework-specific assertion methods over generic assert statements
- Write assertions that clearly communicate intent
- 使用清晰、易读的断言语法
- 优先使用框架特定的断言方法而非通用断言语句
- 编写能清晰传达意图的断言