← ClaudeAtlas

rust-testinglisted

Rust测试模式,包括单元测试、集成测试、异步测试、基于属性的测试、模拟和覆盖率。遵循TDD方法学。
SakulaPor/TemplateAgents · ★ 0 · Testing & QA · score 57
Install: claude install-skill SakulaPor/TemplateAgents
# Rust 测试模式 遵循 TDD 方法论编写可靠、可维护测试的全面 Rust 测试模式。 ## 何时使用 * 编写新的 Rust 函数、方法或特征 * 为现有代码添加测试覆盖率 * 为性能关键代码创建基准测试 * 为输入验证实现基于属性的测试 * 在 Rust 项目中遵循 TDD 工作流 ## 工作原理 1. **识别目标代码** — 找到要测试的函数、特征或模块 2. **编写测试** — 在 `#[cfg(test)]` 模块中使用 `#[test]`,使用 rstest 进行参数化测试,或使用 proptest 进行基于属性的测试 3. **模拟依赖项** — 使用 mockall 来隔离被测单元 4. **运行测试 (RED)** — 验证测试是否按预期失败 5. **实现 (GREEN)** — 编写最少代码以通过测试 6. **重构** — 改进代码同时保持测试通过 7. **检查覆盖率** — 使用 cargo-llvm-cov,目标 80% 以上 ## Rust 的 TDD 工作流 ### RED-GREEN-REFACTOR 循环 ``` RED → Write a failing test first GREEN → Write minimal code to pass the test REFACTOR → Improve code while keeping tests green REPEAT → Continue with next requirement ``` ### Rust 中的分步 TDD ```rust // RED: Write test first, use todo!() as placeholder pub fn add(a: i32, b: i32) -> i32 { todo!() } #[cfg(test)] mod tests { use super::*; #[test] fn test_add() { assert_eq!(add(2, 3), 5); } } // cargo test → panics at 'not yet implemented' ``` ```rust // GREEN: Replace todo!() with minimal implementation pub fn add(a: i32, b: i32) -> i32 { a + b } // cargo test → PASS, then REFACTOR while keeping tests green ``` ## 单元测试 ### 模块级测试组织 ```rust // src/user.rs pub struct User { pub name: String, pub email: String, } impl User { pub fn new(name: impl Into<String>, email: impl Into<String>) -> Result<Self, String> { let email = email.into(); if !email.contains('@') { return Err(format!("invalid email: {email}")); } Ok(Self