Skip to content

测试基础

测试函数

rust
// src/lib.rs
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

pub fn greeting(name: &str) -> String {
    format!("Hello, {}!", name)
}

// 测试模块
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_add() {
        let result = add(2, 3);
        assert_eq!(result, 5);
    }

    #[test]
    fn test_greeting() {
        let result = greeting("Alice");
        assert!(result.contains("Alice"));
        assert_eq!(result, "Hello, Alice!");
    }
}
▶ Run

运行测试

bash
# 运行所有测试
cargo test

# 运行特定测试
cargo test test_add

# 运行测试并显示输出
cargo test -- --nocapture

# 单线程运行(调试并发问题)
cargo test -- --test-threads=1

# 只运行失败的测试
cargo test -- --failed

# 运行忽略的测试
cargo test -- --ignored

# 运行测试,显示简要输出
cargo test -- --quiet

测试输出

running 2 tests
test tests::test_add ... ok
test tests::test_greeting ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

断言宏

常用断言

rust
#[test]
fn test_assertions() {
    // assert! - 条件为真
    assert!(true);
    assert!(2 + 2 == 4);

    // assert! 带错误消息
    assert!(2 + 2 == 4, "数学出错了");

    // assert_eq! - 相等
    assert_eq!(10, 5 + 5);
    assert_eq!("hello", "hel".to_string() + "lo");

    // assert_ne! - 不相等
    assert_ne!(1, 2);
    assert_ne!("hello", "world");

    // 自定义错误消息
    assert_eq!(2 + 2, 4, "加法运算失败");
}
▶ Run

测试 Result 和 Option

rust
#[test]
fn test_result() -> Result<(), String> {
    if 2 + 2 == 4 {
        Ok(())
    } else {
        Err("数学出错了".to_string())
    }
}

#[test]
fn test_option() {
    let value: Option<i32> = Some(5);

    // is_some / is_none
    assert!(value.is_some());
    assert!(!value.is_none());

    // unwrap
    assert_eq!(value.unwrap(), 5);
}
▶ Run

测试 panic

rust
#[test]
#[should_panic]
fn test_panic() {
    panic!("预期的 panic");
}

#[test]
#[should_panic(expected = "预期的 panic")]
fn test_panic_message() {
    panic!("预期的 panic");
}

#[test]
fn test_panic_result() {
    let result = std::panic::catch_unwind(|| {
        panic!("test panic");
    });
    assert!(result.is_err());
}
▶ Run