用途 该技能为 Miyabi 项目提供完整的测试驱动开发(TDD)工作流,通过 Red-Green-Refactor 循环实现健壮、易维护的代码。版本 1.0.0,最后更新于 2025-11-26,优先级为 P0。
调用触发场景 包括:实现新功能(如 "implement feature X"、"add new functionality")、修复缺陷("fix bug"、"resolve issue")、添加测试("add tests"、"write tests for")、带测试的重构("refactor with tests"、"improve code"),以及明确要求 TDD("use TDD"、"test-driven")。
TDD 三阶段 Phase 1 RED:编写会失败的测试,把待实现功能的规格以测试形式明确下来。示例使用 #[cfg(test)] mod tests 与 #[test] 函数,包含 Arrange/Act/Assert 结构及边界用例;执行 cargo test test_new_feature --no-run && cargo test test_new_feature,预期为 FAILED。 Phase 2 GREEN:编写让测试通过的最小实现,示例函数返回 Result<String, Error>,空输入返回 Err(Error::InvalidInput);执行 cargo test test_new_feature,预期 PASSED。 Phase 3 REFACTOR:在保持测试通过的前提下改善代码质量,示例将校验、处理、结果构建拆分为独立函数;执行 cargo test test_new_feature && cargo clippy && cargo fmt -- --check,预期全部测试成功、无警告且格式合规。
测试金字塔 Unit Tests 占 60%,针对函数/方法,要求快速、独立、确定;Integration Tests 占 30%,验证组件间协作并模拟外部 API;E2E Tests 占 10%,覆盖完整用户流程、接近生产环境。各层级参考:Unit 覆盖率目标 80%+、单测执行 <1 秒、常时运行;Integration 覆盖关键路径、<10 秒、CI 运行;E2E 覆盖关键流程、<60 秒、每日运行。
Rust TDD 模式集 提供六类模式:Result 型测试(成功与错误分支,使用 matches! 校验错误类型)、async 函数测试(#[tokio::test],含超时测试)、Mock 使用(mockall 的 mock! 与 expect_call)、属性测试(proptest,含往返编解码校验)、测试夹具(TestFixture 的 new/teardown)、快照测试(insta 的 assert_snapshot!)。
命令参考 基础命令包括 cargo test --workspace、cargo test -p miyabi-agents、cargo test test_name、cargo test workflow_、cargo test -- --test-threads=1、cargo test -- --nocapture、cargo test -- --show-output。高级命令包括 cargo test --doc、cargo test --test integration_test、cargo bench、cargo llvm-cov --workspace --html、PROPTEST_CASES=10000 cargo test。CI 命令为 cargo test --workspace --all-features && cargo clippy --workspace --all-targets --all-features -- -D warnings && cargo fmt --all -- --check,以及 cargo llvm-cov --workspace --lcov --output-path lcov.info。
测试结构 目录结构示例:crates/miyabi-xxx/ 下含 src/lib.rs 与 src/feature.rs、tests/integration_test.rs 与 tests/e2e_test.rs、benches/benchmark.rs。测试模块可按 success_cases、error_cases、edge_cases 分组。
最佳实践 推荐:一测试一断言、AAA 模式、表意清晰的测试名(如 when_input_is_empty_returns_validation_error)、显式测试数据。不推荐:测试间存在依赖(如 static mut 共享状态)、测试实现细节(如断言内部缓存长度)、非确定性测试(如依赖时间)、过度复杂的初始化代码。
覆盖率指南 目标:Core Types 90%+(P0)、Business Logic 85%+(P0)、API Handlers 80%+(P1)、Utilities 70%+(P2)、CLI 60%+(P2)。测量方式:cargo install cargo-llvm-cov,然后 cargo llvm-cov --workspace --html,报告位于 target/llvm-cov/html/index.html。可用 #[cfg(not(tarpaulin_include))] 或 #[coverage(off)] 排除。
CI/CD 集成 提供 GitHub Actions 配置示例:检出代码、安装 Rust(dtolnay/rust-action@stable)、运行测试、Clippy 检查、格式检查、生成 lcov 覆盖率并上传至 codecov。
故障排查 测试不稳定:禁用并行(--test-threads=1)、开启 RUST_LOG=debug、循环运行 100 次。测试过慢:cargo build --timings、--report-time、调整并行度。Mock 不生效:使用 mock.checkpoint() 校验调用,或使用更具体的匹配器与 times(1)。
成功标准 Unit 与 Integration 测试 100% 通过、覆盖率 >80%、cargo clippy 无警告、cargo fmt 格式合规。输出格式包含 RED/GREEN/REFACTOR 各阶段结果、覆盖率、Clippy 与格式状态,以及 "Ready to commit"。
相关文档与技能 相关文档:context/rust.md(Rust 开发指南)、Skills/rust-development/(Rust 构建工作流)、Skills/debugging-troubleshooting/(调试支持)。相关技能:Rust Development、Debugging Troubleshooting、Git Workflow、Security Audit。