[rust]测试

21 阅读1分钟

创建一个库package:

  1. 通过#[cfg(test)]标识测试模块
  2. 通过#[test]标识测试方法
  3. 可以通过通配符*的方式导入所有公共子模块
  4. 通过cargo test运行所有测试函数

src/lib.rs

pub fn add(left: u64, right: u64) -> u64 {
    left + right
}

// src/america.rs
pub mod america;

#[cfg(test)]
mod tests {
    // 使用模块
    use super::*;
    // 使用子模块
    use america::animal::*;

    #[test]
    fn it_works() {
        let result = add(2, 2);
        assert_eq!(result, 4);
    }

    #[test]
    fn america_zoo(){
        america::say_welcome()
    }

    #[test]
    fn animal_say(){
        // 子模块方法调用
        dog::say();
        goose::say();
    }
}

src/america.rs

pub fn say_welcome() {
    println!("welcome to USA zoo")
}

pub mod animal {
    pub mod goose {
        pub fn say() {
            println!("ga ga")
        }
    }

    pub mod dog {
        pub fn say() {
            println!("wang wang")
        }
    }
}

其他:

  1. 比如在测试中调用了 println! 而测试通过了,我们将不会在终端看到 println! 的输出:只会看到说明测试通过的提示行。如果测试失败了,则会看到所有标准输出和其他错误信息
  2. 执行cargo test -- --show-output来执行所有的单测,并输出测试中打印的值
  3. 执行cargo test your_method_name -- --show-output,来执行特定的单测,并输出测试中打印的值