#[test] 单元测试 ​

核心概念 ​

#[test] 属性标注一个函数为测试函数,cargo test 会自动发现并运行所有带 #[test] 标注的函数。单元测试通常写在与被测试代码相同的文件中,放在 #[cfg(test)] mod tests { ... } 模块内。测试函数没有参数,返回 () 或 Result<(), E>。

Rust 的测试框架是内置的,不需要额外依赖。测试通过断言宏(assert!、assert_eq!、assert_ne!)来验证行为。测试函数 panic 表示失败,正常返回表示通过。

rust
// 被测试的函数
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

pub fn divide(a: f64, b: f64) -> Result<f64, String> {
    if b == 0.0 {
        Err("除数不能为零".to_string())
    } else {
        Ok(a / b)
    }
}

// 测试模块
#[cfg(test)]
mod tests {
    use super::*;  // 导入父模块的所有公共和私有项

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

    #[test]
    fn test_divide() {
        assert_eq!(divide(10.0, 2.0), Ok(5.0));
    }

    #[test]
    fn test_divide_by_zero() {
        assert!(divide(10.0, 0.0).is_err());
    }

    // 返回 Result 的测试(可以使用 ? 运算符)
    #[test]
    fn test_divide_result() -> Result<(), String> {
        let result = divide(10.0, 2.0)?;
        assert_eq!(result, 5.0);
        Ok(())
    }
}

fn main() {
    println!("运行 cargo test 执行所有测试");
}

断言宏 ​

rust
#[cfg(test)]
mod tests {
    #[test]
    fn test_assertions() {
        // assert! — 条件为 true 则通过
        assert!(1 + 1 == 2);
        assert!(true);

        // assert_eq! — 两个值相等则通过
        assert_eq!(2 + 2, 4);
        assert_eq!("hello".to_string(), String::from("hello"));

        // assert_ne! — 两个值不相等则通过
        assert_ne!(1, 2);
        assert_ne!("hello", "world");

        // 带自定义错误消息
        let x = 42;
        assert!(x > 0, "x 应该大于 0,实际值: {}", x);
        assert_eq!(x, 42, "x 应该等于 42,实际值: {}", x);
        assert_ne!(x, 0, "x 不应该为 0");
    }

    #[test]
    fn test_debug_assert() {
        // debug_assert! 只在 debug 构建中检查
        // 测试默认是 debug 构建,所以会执行
        debug_assert!(true);
        debug_assert_eq!(1, 1);
        debug_assert_ne!(1, 2);
    }
}
宏说明失败时输出
assert!(expr)表达式为 true"assertion failed"
assert_eq!(a, b)a == b显示两个值的 Debug 输出
assert_ne!(a, b)a != b显示两个值的 Debug 输出
assert!(expr, "msg", args)带自定义消息自定义消息

测试私有函数 ​

rust
// Rust 的单元测试可以直接测试私有函数
// 因为 #[cfg(test)] mod tests 是当前模块的子模块

fn private_helper(x: i32) -> i32 {
    x * 2 + 1
}

pub fn public_api(x: i32) -> i32 {
    private_helper(x) + 10
}

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

    // 可以直接测试私有函数
    #[test]
    fn test_private_helper() {
        assert_eq!(private_helper(5), 11);
        assert_eq!(private_helper(0), 1);
    }

    #[test]
    fn test_public_api() {
        assert_eq!(public_api(5), 21);
    }
}

fn main() {
    println!("result = {}", public_api(5));
}

常用测试命令 ​

bash
# 运行所有测试
# cargo test

# 运行特定名称的测试
# cargo test test_add

# 运行匹配模式的测试
# cargo test divide    (运行名称包含 "divide" 的测试)

# 显示测试输出(默认测试通过时不显示 println 输出)
# cargo test -- --show-output

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

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

# 列出所有测试但不运行
# cargo test -- --list

基本示例 ​

rust
// 一个完整的单元测试示例

#[derive(Debug, PartialEq)]
pub struct Calculator {
    history: Vec<f64>,
}

impl Calculator {
    pub fn new() -> Self {
        Calculator { history: Vec::new() }
    }

    pub fn add(&mut self, a: f64, b: f64) -> f64 {
        let result = a + b;
        self.history.push(result);
        result
    }

    pub fn subtract(&mut self, a: f64, b: f64) -> f64 {
        let result = a - b;
        self.history.push(result);
        result
    }

    pub fn last_result(&self) -> Option<f64> {
        self.history.last().copied()
    }

    pub fn history_count(&self) -> usize {
        self.history.len()
    }

    pub fn clear(&mut self) {
        self.history.clear();
    }
}

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

    // 每个测试函数独立运行,不共享状态
    #[test]
    fn test_new_calculator() {
        let calc = Calculator::new();
        assert_eq!(calc.history_count(), 0);
        assert_eq!(calc.last_result(), None);
    }

    #[test]
    fn test_add() {
        let mut calc = Calculator::new();
        assert_eq!(calc.add(2.0, 3.0), 5.0);
        assert_eq!(calc.last_result(), Some(5.0));
    }

    #[test]
    fn test_subtract() {
        let mut calc = Calculator::new();
        assert_eq!(calc.subtract(10.0, 4.0), 6.0);
    }

    #[test]
    fn test_history() {
        let mut calc = Calculator::new();
        calc.add(1.0, 2.0);
        calc.subtract(5.0, 3.0);
        assert_eq!(calc.history_count(), 2);
    }

    #[test]
    fn test_clear() {
        let mut calc = Calculator::new();
        calc.add(1.0, 1.0);
        calc.clear();
        assert_eq!(calc.history_count(), 0);
        assert_eq!(calc.last_result(), None);
    }
}

fn main() {
    let mut calc = Calculator::new();
    println!("{}", calc.add(10.0, 20.0));
    println!("{}", calc.subtract(50.0, 15.0));
    println!("历史记录数: {}", calc.history_count());
}

常见问题 ​

问题一:#[cfg(test)] 有什么作用?

#[cfg(test)] 让被标注的模块只在测试编译时存在。正常的 cargo build 不会编译测试代码,减小二进制体积。测试模块中的 use super::* 可以访问父模块的私有项。

问题二:测试是并行运行的吗?

默认是并行的。每个测试函数在独立的线程中运行。如果测试之间有共享状态(如文件、全局变量),用 -- --test-threads=1 强制串行。

问题三:测试函数可以返回 Result 吗?

可以。返回 Result<(), E> 的测试函数在返回 Err 时视为失败。这让测试中可以使用 ? 运算符,代码更简洁。

问题四:怎么测试 panic 行为?

用 #[should_panic] 属性标注,详见 17.29 节。也可以用 std::panic::catch_unwind 手动捕获。

适用场景 ​

  • 函数正确性验证:测试输入输出是否符合预期
  • 边界条件测试:空输入、最大值、零值等
  • 回归测试:修复 bug 后添加测试防止重现
  • 重构保障:修改实现时确保行为不变

注意事项 ​

  • 测试函数没有参数,返回 () 或 Result<(), E>
  • #[cfg(test)] 模块只在测试编译时存在
  • 测试默认并行运行,注意共享状态
  • assert_eq! 和 assert_ne! 要求类型实现 Debug 和 PartialEq
  • 通过的测试默认不显示 println! 输出
  • 每个测试函数独立运行,不共享状态

总结 ​

#[test] 标注测试函数,cargo test 自动发现并运行。测试通过断言宏(assert!、assert_eq!、assert_ne!)验证行为,panic 表示失败。单元测试写在 #[cfg(test)] mod tests 中,可以测试私有函数。测试默认并行运行。返回 Result<(), E> 的测试可以使用 ? 运算符。cargo test name 运行匹配名称的测试,-- --show-output 显示打印输出。