rust-testing
FeaturedRust测试模式,包括单元测试、集成测试、异步测试、基于属性的测试、模拟和覆盖率。遵循TDD方法学。
Testing & QA 308,704 stars
45417 forks Updated 2 days ago MIT
Install
Quality Score: 95/100
Stars 20%
Recency 20%
Frontmatter 20%
Documentation 15%
Issue Health 10%
License 10%
Description 5%
Skill Content
# 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 → 先写一个失败的测试
GREEN → 编写最少代码使测试通过
REFACTOR → 重构代码,同时保持测试通过
REPEAT → 继续下一个需求
```
### 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 { name: name.into(), email })
}
pub fn display_name(&self) -> &str {
&s...
Details
- Author
- affaan-m
- Repository
- affaan-m/everything-claude-code
- Created
- 10 months ago
- Last Updated
- 2 days ago
- Language
- JavaScript
- License
- MIT
Integrates with
Similar Skills
Semantically similar based on skill content — not just same category
Testing & QA Listed
rust-testing
Rust测试模式,包括单元测试、集成测试、异步测试、基于属性的测试、模拟和覆盖率。遵循TDD方法学。
0 Updated 8 months ago
SakulaPor Testing & QA Listed
rust-testing
Rust testing patterns including unit tests, integration tests, async testing, property-based testing, mocking, and coverage. Follows TDD methodology.
2 Updated 7 months ago
caovinhphuc Testing & QA Listed
rust-testing
Rust testing patterns including unit tests, integration tests, async testing, property-based testing, mocking, and coverage. Follows TDD methodology.
14 Updated today
tincopper