创建一个库package:
- 通过
#[cfg(test)]
标识测试模块 - 通过
#[test]
标识测试方法 - 可以通过通配符
*
的方式导入所有公共子模块 - 通过
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")
}
}
}
其他:
- 比如在测试中调用了
println!
而测试通过了,我们将不会在终端看到println!
的输出:只会看到说明测试通过的提示行。如果测试失败了,则会看到所有标准输出和其他错误信息 - 执行
cargo test -- --show-output
来执行所有的单测,并输出测试中打印的值 - 执行
cargo test your_method_name -- --show-output
,来执行特定的单测,并输出测试中打印的值