文档测试 doctest
核心概念
文档测试(doctest)是 Rust 将文档注释中的代码块自动作为测试运行的机制。cargo test 会提取 /// 和 //! 注释中所有未标记 ignore 的代码块,将每个代码块编译为独立的小程序并运行。文档测试是 Rust 保证文档与代码同步的关键手段。
文档测试与单元测试和集成测试一起构成 Rust 的三层测试体系。cargo test 的输出会分别显示单元测试、集成测试和文档测试的结果。
/// 将摄氏度转为华氏度
///
/// ```
/// let f = celsius_to_fahrenheit(100.0);
/// assert_eq!(f, 212.0);
///
/// let f = celsius_to_fahrenheit(0.0);
/// assert_eq!(f, 32.0);
/// ```
pub fn celsius_to_fahrenheit(c: f64) -> f64 {
c * 9.0 / 5.0 + 32.0
}
/// 将华氏度转为摄氏度
///
/// ```
/// let c = fahrenheit_to_celsius(212.0);
/// assert!((c - 100.0).abs() < f64::EPSILON);
/// ```
pub fn fahrenheit_to_celsius(f: f64) -> f64 {
(f - 32.0) * 5.0 / 9.0
}
fn main() {
println!("100°C = {}°F", celsius_to_fahrenheit(100.0));
}三层测试体系
| 测试类型 | 位置 | 运行命令 | 用途 |
|---|---|---|---|
| 单元测试 | src/ 中 #[cfg(test)] | cargo test --lib | 内部逻辑验证 |
| 集成测试 | tests/ 目录 | cargo test --tests | 公共 API 验证 |
| 文档测试 | /// 和 //! 注释 | cargo test --doc | 文档示例验证 |
# cargo test 的输出示例:
#
# running 5 tests ← 单元测试
# test tests::test_add ... ok
# ...
#
# running 2 tests ← 集成测试
# test api_test::test_endpoint ... ok
# ...
#
# running 3 tests ← 文档测试
# test src/lib.rs - celsius_to_fahrenheit (line 3) ... ok
# ...文档测试的编译过程
/// 加法函数
///
/// ```
/// assert_eq!(add(2, 3), 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
// 上面的文档测试会被编译为类似这样的独立程序:
//
// extern crate my_crate;
// use my_crate::add;
//
// fn main() {
// assert_eq!(add(2, 3), 5);
// }
//
// 每个代码块是独立编译的,互不影响
fn main() {
println!("文档测试被自动包装在 fn main() 中");
}控制文档测试行为
/// 各种标记的效果
///
/// 正常测试(编译 + 运行):
/// ```
/// assert_eq!(1 + 1, 2);
/// ```
///
/// 只编译不运行(`no_run`):
/// ```no_run
/// // 这段代码会被编译但不运行
/// // 适合有副作用的示例(如写文件、启动服务器)
/// std::fs::write("/tmp/test.txt", "hello").unwrap();
/// ```
///
/// 完全跳过(`ignore`):
/// ```ignore
/// // 不编译也不运行
/// // 适合伪代码或不完整的示例
/// let x = some_unresolved_function();
/// ```
///
/// 预期编译失败(`compile_fail`):
/// ```compile_fail
/// // 验证某些代码确实无法编译
/// let x: i32 = "hello"; // 类型不匹配
/// ```
///
/// 隐藏辅助行(`#` 开头):
/// ```
/// # fn helper() -> i32 { 42 }
/// // 用户只看到这行
/// let result = helper();
/// assert_eq!(result, 42);
/// ```
pub fn documented_function() {}
fn main() {}基本示例
//! # 字符串工具库
//!
//! 模块级文档中的代码也会被测试:
//!
//! ```
//! let result = reverse_string("hello");
//! assert_eq!(result, "olleh");
//! ```
/// 反转字符串
///
/// 正确处理 Unicode 字符。
///
/// ```
/// // 基本用法
/// assert_eq!(reverse_string("hello"), "olleh");
/// assert_eq!(reverse_string(""), "");
/// assert_eq!(reverse_string("a"), "a");
///
/// // Unicode
/// assert_eq!(reverse_string("你好"), "好你");
/// ```
pub fn reverse_string(s: &str) -> String {
s.chars().rev().collect()
}
/// 重复字符串 n 次
///
/// ```
/// assert_eq!(repeat_string("ab", 3), "ababab");
/// assert_eq!(repeat_string("x", 0), "");
/// ```
pub fn repeat_string(s: &str, n: usize) -> String {
s.repeat(n)
}
/// 截断字符串到指定长度,超出部分用 "..." 替代
///
/// ```
/// assert_eq!(truncate_with_ellipsis("hello world", 5), "hello...");
/// assert_eq!(truncate_with_ellipsis("hi", 10), "hi");
/// ```
pub fn truncate_with_ellipsis(s: &str, max_len: usize) -> String {
if s.chars().count() <= max_len {
s.to_string()
} else {
let truncated: String = s.chars().take(max_len).collect();
format!("{}...", truncated)
}
}
fn main() {
println!("{}", reverse_string("Rust"));
println!("{}", repeat_string("ha", 3));
println!("{}", truncate_with_ellipsis("Hello, World!", 5));
}常见问题
问题一:文档测试和 #[test] 单元测试有什么区别?
文档测试写在注释中,每个代码块独立编译。单元测试写在 #[cfg(test)] 模块中,与库代码一起编译。文档测试的主要目的是保证文档示例的正确性,单元测试的目的是全面的功能验证。
问题二:文档测试可以访问私有 API 吗?
不能。文档测试被编译为独立的外部 crate,只能访问公共 API。这也意味着文档测试展示的是用户实际使用的方式。
问题三:文档测试编译太慢怎么办?
每个代码块独立编译,代码块越多编译越慢。可以将相关的断言合并到一个代码块中。也可以用 cargo test --lib 只运行单元测试,跳过文档测试。
问题四:文档测试中怎么使用当前 crate?
Cargo 会自动添加 extern crate 声明。直接使用公共 API 即可,不需要手动写 use 或 extern crate(但如果需要特定导入,可以用 # 隐藏行)。
适用场景
- API 文档验证:确保文档中的示例始终可运行
- 使用方式说明:用可验证的代码展示 API 用法
- 回归防护:API 变更时文档测试会自动失败
- 新用户引导:文档中的示例即是可运行的教程
注意事项
- 每个代码块独立编译为独立程序
- 只能访问公共 API
#隐藏行会被编译但不在文档中显示no_run编译但不运行,适合有副作用的代码cargo test --doc只运行文档测试- 合并代码块可以减少编译时间
总结
文档测试将 /// 和 //! 注释中的代码块作为独立程序编译和运行,确保文档示例始终正确。cargo test 会同时运行单元测试、集成测试和文档测试。通过标记控制行为:默认编译+运行、no_run 只编译、ignore 跳过、compile_fail 预期编译失败。# 开头的行会被编译但不在文档中显示。文档测试只能访问公共 API,展示的是用户实际使用方式。cargo test --doc 单独运行文档测试。