rust-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rust Testing Best Practices

Rust测试最佳实践

Comprehensive testing guide for Rust applications, covering CLI testing, library testing, async patterns, and CI integration. Contains 42 rules across 8 categories, prioritized by impact to guide test design, mocking strategies, and CI optimization.
这是一份针对Rust应用的全面测试指南,涵盖CLI测试、库测试、异步模式以及CI集成。包含8个类别下的42条规则,按影响优先级排序,用于指导测试设计、模拟策略和CI优化。

When to Apply

适用场景

Reference these guidelines when:
  • Writing unit tests for Rust libraries or modules
  • Creating integration tests for CLI applications
  • Setting up mocking with mockall or trait-based design
  • Testing async code with Tokio
  • Configuring CI pipelines for Rust projects
在以下场景中参考本指南:
  • 为Rust库或模块编写单元测试
  • 为CLI应用创建集成测试
  • 使用mockall或基于trait的设计设置模拟
  • 使用Tokio测试异步代码
  • 为Rust项目配置CI流水线

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Test OrganizationCRITICAL
org-
2Mocking and Test DoublesCRITICAL
mock-
3Async TestingHIGH
async-
4Property-Based TestingHIGH
prop-
5Test Fixtures and SetupMEDIUM
fix-
6Assertions and Error TestingMEDIUM
assert-
7CI IntegrationMEDIUM
ci-
8Test PerformanceLOW-MEDIUM
perf-
优先级类别影响程度前缀
1测试组织关键
org-
2模拟与测试替身关键
mock-
3异步测试
async-
4属性化测试
prop-
5测试夹具与初始化
fix-
6断言与错误测试
assert-
7CI集成
ci-
8测试性能低-中
perf-

Quick Reference

快速参考

1. Test Organization (CRITICAL)

1. 测试组织(关键)

  • org-unit-test-modules
    - Use cfg(test) modules for unit tests
  • org-integration-tests-directory
    - Place integration tests in tests directory
  • org-shared-test-utilities
    - Use tests/common/mod.rs for shared utilities
  • org-binary-crate-pattern
    - Extract logic from main.rs into lib.rs
  • org-test-naming
    - Name tests after behavior not implementation
  • org-test-cli-with-assert-cmd
    - Use assert_cmd for CLI testing
  • org-unit-test-modules
    - 使用cfg(test)模块编写单元测试
  • org-integration-tests-directory
    - 将集成测试放在tests目录中
  • org-shared-test-utilities
    - 使用tests/common/mod.rs存放共享工具
  • org-binary-crate-pattern
    - 将main.rs中的逻辑提取到lib.rs
  • org-test-naming
    - 按行为而非实现命名测试
  • org-test-cli-with-assert-cmd
    - 使用assert_cmd进行CLI测试

2. Mocking and Test Doubles (CRITICAL)

2. 模拟与测试替身(关键)

  • mock-trait-based-design
    - Design for testability with traits
  • mock-automock-attribute
    - Use mockall automock for complex mocking
  • mock-avoid-mocking-owned-types
    - Avoid mocking types you own
  • mock-expect-call-counts
    - Verify mock call counts explicitly
  • mock-predicate-arguments
    - Use predicates to verify mock arguments
  • mock-returning-sequences
    - Use sequences for multiple return values
  • mock-static-methods
    - Use mock! macro for static methods
  • mock-trait-based-design
    - 基于trait设计以提升可测试性
  • mock-automock-attribute
    - 使用mockall的automock进行复杂模拟
  • mock-avoid-mocking-owned-types
    - 避免模拟你自己拥有的类型
  • mock-expect-call-counts
    - 显式验证模拟的调用次数
  • mock-predicate-arguments
    - 使用谓词验证模拟的参数
  • mock-returning-sequences
    - 使用序列处理多返回值
  • mock-static-methods
    - 使用mock!宏模拟静态方法

3. Async Testing (HIGH)

3. 异步测试(高)

  • async-tokio-test-macro
    - Use tokio::test for async test functions
  • async-time-control
    - Use paused time for timeout testing
  • async-mock-io
    - Use tokio_test for mocking async IO
  • async-spawn-blocking
    - Test spawn_blocking with multi-threaded runtime
  • async-test-channels
    - Use channels for testing async communication
  • async-tokio-test-macro
    - 使用tokio::test标记异步测试函数
  • async-time-control
    - 使用暂停时间进行超时测试
  • async-mock-io
    - 使用tokio_test模拟异步IO
  • async-spawn-blocking
    - 使用多线程运行时测试spawn_blocking
  • async-test-channels
    - 使用通道测试异步通信

4. Property-Based Testing (HIGH)

4. 属性化测试(高)

  • prop-proptest-basics
    - Use proptest for property-based testing
  • prop-custom-strategies
    - Create custom strategies for domain types
  • prop-shrinking
    - Use shrinking to find minimal failing cases
  • prop-invariant-testing
    - Test invariants instead of specific values
  • prop-proptest-basics
    - 使用proptest进行属性化测试
  • prop-custom-strategies
    - 为领域类型创建自定义策略
  • prop-shrinking
    - 使用收缩功能找到最小失败用例
  • prop-invariant-testing
    - 测试不变量而非特定值

5. Test Fixtures and Setup (MEDIUM)

5. 测试夹具与初始化(中)

  • fix-rstest-fixtures
    - Use rstest fixtures for test setup
  • fix-rstest-parametrized
    - Use rstest case for parameterized tests
  • fix-temp-directories
    - Use TempDir for file system tests
  • fix-test-context
    - Use test-context for setup and teardown
  • fix-once-cell-shared-state
    - Use OnceCell for expensive shared setup
  • fix-rstest-fixtures
    - 使用rstest夹具进行测试初始化
  • fix-rstest-parametrized
    - 使用rstest case进行参数化测试
  • fix-temp-directories
    - 使用TempDir进行文件系统测试
  • fix-test-context
    - 使用test-context进行初始化和清理
  • fix-once-cell-shared-state
    - 使用OnceCell处理昂贵的共享初始化

6. Assertions and Error Testing (MEDIUM)

6. 断言与错误测试(中)

  • assert-specific-errors
    - Assert specific error types not just is_err
  • assert-should-panic
    - Use should_panic for panic testing
  • assert-debug-display
    - Implement Debug for clear failure messages
  • assert-custom-messages
    - Add context to assertions with custom messages
  • assert-floating-point
    - Use approximate comparison for floating point
  • assert-collection-contents
    - Assert collection contents not just length
  • assert-specific-errors
    - 断言特定错误类型而非仅检查is_err
  • assert-should-panic
    - 使用should_panic测试panic场景
  • assert-debug-display
    - 实现Debug以获得清晰的失败信息
  • assert-custom-messages
    - 为断言添加自定义上下文信息
  • assert-floating-point
    - 对浮点数使用近似比较
  • assert-collection-contents
    - 断言集合内容而非仅检查长度

7. CI Integration (MEDIUM)

7. CI集成(中)

  • ci-cargo-nextest
    - Use cargo-nextest for faster CI
  • ci-caching
    - Cache Cargo dependencies in CI
  • ci-test-isolation
    - Ensure test isolation in parallel CI
  • ci-coverage
    - Generate coverage reports in CI
  • ci-cargo-nextest
    - 使用cargo-nextest加速CI测试
  • ci-caching
    - 在CI中缓存Cargo依赖
  • ci-test-isolation
    - 确保并行CI中的测试隔离
  • ci-coverage
    - 在CI中生成覆盖率报告

8. Test Performance (LOW-MEDIUM)

8. 测试性能(低-中)

  • perf-compile-time
    - Reduce test compilation time
  • perf-test-filtering
    - Filter tests for faster feedback loops
  • perf-avoid-io-in-unit-tests
    - Avoid real IO in unit tests
  • perf-parallel-test-execution
    - Configure parallel test threads
  • perf-benchmark-critical-paths
    - Benchmark critical paths with Criterion
  • perf-compile-time
    - 减少测试编译时间
  • perf-test-filtering
    - 过滤测试以获得更快的反馈循环
  • perf-avoid-io-in-unit-tests
    - 在单元测试中避免真实IO操作
  • perf-parallel-test-execution
    - 配置并行测试线程
  • perf-benchmark-critical-paths
    - 使用Criterion对关键路径进行基准测试

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Rule template - Template for adding new rules
阅读单个参考文件以获取详细说明和代码示例:
  • 章节定义 - 类别结构和影响级别
  • 规则模板 - 添加新规则的模板

Reference Files

参考文件

FileDescription
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
metadata.jsonVersion and reference information
文件描述
references/_sections.md类别定义与排序
assets/templates/_template.md新规则模板
metadata.json版本与参考信息