4.2 其他类型的测试

02-其他类型的测试 — Comprehensive Rust

译文 · 基于 Comprehensive Rust

原文链接: https://google.github.io/comprehensive-rust/testing/other.html

4.2 其他类型的测试

集成测试

若要以客户端身份测试你的库,请使用集成测试。

在 tests/ 下创建 .rs 文件:

1
2
3
4
5
6
7
8
9
// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
// tests/my_library.rs
use my_library::init;

#[test]
fn test_init() {
    assert!(init().is_ok());
}

这些测试只能访问你的 crate 的公共 API。

文档测试

Rust 内置支持文档测试:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
/// 将字符串缩短到给定长度。
///
/// ```
/// # use playground::shorten_string;
/// assert_eq!(shorten_string("Hello World", 5), "Hello");
/// assert_eq!(shorten_string("Hello World", 20), "Hello World");
/// ```
pub fn shorten_string(s: &str, length: usize) -> &str {
    &s[..std::cmp::min(length, s.len())]
}
  • /// 注释中的代码块会自动被视为 Rust 代码。
  • 这些代码会在 cargo test 时被编译并执行。
  • 在代码前加 # 会在文档中隐藏该行,但仍会编译/运行。
  • 可在 Rust Playground 上测试上面的代码。
最后修改 August 11, 2026: 更新 (70a5af133)