4.1 单元测试

01-单元测试 — Comprehensive Rust

译文 · 基于 Comprehensive Rust

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

4.1 单元测试

Rust 与 Cargo 自带简单的单元测试框架。测试用 #[test] 标记。单元测试常放在嵌套的 tests 模块中,并用 #[cfg(test)] 仅在构建测试时条件编译。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Copyright 2022 Google LLC
// SPDX-License-Identifier: Apache-2.0
fn first_word(text: &str) -> &str {
    match text.find(' ') {
        Some(idx) => &text[..idx],
        None => &text,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty() {
        assert_eq!(first_word(""), "");
    }

    #[test]
    fn test_single_word() {
        assert_eq!(first_word("Hello"), "Hello");
    }

    #[test]
    fn test_multiple_words() {
        assert_eq!(first_word("Hello World"), "Hello");
    }
}
  • 这样可以对私有辅助函数做单元测试。
  • #[cfg(test)] 属性仅在运行 cargo test 时生效。
最后修改 August 11, 2026: 更新 (70a5af133)