Rust 单元测试:Criterion 与 Integration Test
·
Rust 测试:Criterion 基准测试与集成测试
1. 单元测试与内置测试框架
Rust 内置 #[test] 属性实现单元测试,通常放在模块内:
#[cfg(test)]
mod tests {
#[test]
fn test_addition() {
assert_eq!(2 + 2, 4);
}
}
- 位置:与业务代码同文件(使用
mod tests隔离) - 范围:测试单个函数或模块
- 运行:
cargo test
2. Criterion 基准测试
Criterion 用于性能测试,需在 Cargo.toml 添加依赖:
[dev-dependencies]
criterion = "0.4"
基准测试示例(测量函数耗时):
use criterion::{criterion_group, criterion_main, Criterion};
fn fibonacci(n: u64) -> u64 {
match n {
0 => 1,
1 => 1,
_ => fibonacci(n-1) + fibonacci(n-2),
}
}
fn bench_fib(c: &mut Criterion) {
c.bench_function("fib 20", |b| b.iter(|| fibonacci(20)));
}
criterion_group!(benches, bench_fib);
criterion_main!(benches);
- 特点:
- 统计执行时间分布(纳秒级精度)
- 生成 HTML 报告(
target/criterion)
- 运行:
cargo bench
3. 集成测试(Integration Test)
测试公共 API 接口,需在项目根目录创建 tests/ 目录:
project/
├── src/
└── tests/ <-- 集成测试目录
└── api_test.rs
示例测试文件 tests/api_test.rs:
use my_crate; // 导入待测库
#[test]
fn test_public_api() {
assert_eq!(my_crate::add(3, 5), 8);
}
- 规则:
- 每个文件编译为独立可执行文件
- 只能调用
pub公开接口 - 测试间无共享状态
- 运行:
cargo test --test api_test
4. 对比总结
| 测试类型 | 位置 | 作用 | 依赖 |
|---|---|---|---|
| 单元测试 | src/*.rs 内 |
验证函数逻辑 | Rust 内置 |
| Criterion 基准测试 | benches/*.rs |
测量性能指标 | criterion |
| 集成测试 | tests/*.rs |
验证公共 API 行为 | Rust 内置 |
5. 最佳实践建议
- 单元测试:
- 覆盖所有边界条件(如空输入、极端值)
- 使用
#[should_panic]测试异常情况
- Criterion:
- 避免在迭代器内执行耗时操作(
b.iter(|| ...)) - 使用
c.bench_with_input测试多组输入
- 避免在迭代器内执行耗时操作(
- 集成测试:
- 模拟外部服务(如用
mockito模拟 HTTP) - 结合
#[ignore]标记耗时测试
- 模拟外部服务(如用
完整示例项目结构:
my_project/ ├── Cargo.toml ├── src/ ├── benches/ # Criterion 基准测试 │ └── bench.rs └── tests/ # 集成测试 └── api.rs
更多推荐
所有评论(0)