Z
ZHANK
编程在线教程Rust 教程测试与文档测试
工程化

测试与文档测试

#[test] 单元测试、#[cfg(test)] 模块、集成测试 tests/、文档测试

测试与文档测试

Rust 测试内置在语言中——#[test] 标记测试函数,cargo test 运行。文档注释中的代码块也能作为测试运行。

学完本章你将: 掌握 #[test] 单元测试、#[cfg(test)]、集成测试 tests/、文档测试。


单元测试

rust
// 在同一个文件中
pub fn add(a: i32, b: i32) -> i32 { a + b }

#[cfg(test)]  // 只在测试时编译
mod tests {
    use super::*;

    #[test]
    fn test_add() {
        assert_eq!(add(2, 3), 5);
        assert_ne!(add(0, 0), 1);
    }

    #[test]
    #[should_panic(expected = "除零")]
    fn test_divide_by_zero() {
        divide(10, 0);
    }

    #[test]
    #[ignore]  // 默认不运行
    fn expensive_test() { }
}
bash
cargo test                  # 运行所有测试
cargo test test_add         # 运行特定测试
cargo test -- --ignored     # 运行被忽略的测试
cargo test -- --test-threads=1  # 单线程运行

集成测试

rust
// tests/integration_test.rs(项目根目录的 tests/ 文件夹)
use mylib;

#[test]
fn integration_test() {
    assert_eq!(mylib::add(2, 3), 5);
}

文档测试

rust
/// 把两个数字相加
///
/// ```
/// let result = mylib::add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 { a + b }
bash
cargo test  # 文档中的代码块也会被编译运行!