结论:三类测试各有约定位置:单元测试写在源文件内的 #[cfg(test)] mod tests 里,可访问私有项;集成测试放在 tests/ 目录,每个文件编译成独立 crate,只能通过公共 API 测试;doc test 写在文档注释的 ``` 代码块里,cargo test 会编译运行它们,保证示例代码不过期。
展开:实践要点:1)单元测试用 #[cfg(test)] 门控,正常构建完全剔除,配合 super::* 引入被测代码;测试函数标 #[test],panic 即失败,should_panic 验证预期的 panic。2)集成测试模拟真实用户视角,适合测 crate 对外契约;共享辅助代码放 tests/common/mod.rs(mod.rs 命名避免被当作测试文件)。3)doc test 默认编译运行,隐藏准备代码用 # 前缀行;no_run/ignore/compile_fail 标注控制行为,compile_fail 还能验证类型系统拒绝非法用法。易错点:tests/ 下每个文件是独立二进制,文件多时链接慢,可合并为单文件多 mod;异步测试需要 #[tokio::test] 之类的运行时宏。
/// 计算两个数之和
/// ```
/// assert_eq!(mycrate::add(2, 3), 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 { a + b }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds() { assert_eq!(add(2, 3), 5); }
}
追问方向:快照测试(insta)、属性测试(proptest)与单元测试的互补关系。