运行测试
在函数上加#[test],可以把函数变为测试函数
使用cargo test命令来执行测试函数
mod tests {
#[test]
fn it_works1() {
let result = 2 + 2;
assert_eq!(result, 4);
}
#[test]
fn it_works2() {
let result = 2 + 2;
assert_eq!(result, 4);
}
}
//running 2 tests
//test tests::it_works1 ... ok
//test tests::it_works2 ... ok
-
断言(Assert)
assert!:用来确定某个状态是否为true
assert_eq!和assert_ne!测试相等性
#[should_panic]加在方法前面,方法出现panic测试通过,不出现panic测试失败
#[should_panic(expected = "***")],加入expected参数可以进行对选定panic测试通过
为cargo test添加命令行参数来改变cargo test的行为
cargo test --help:显示cargo test ***的所有参数
cargo test -- --help:显示cargo test --***的所有参数
cargo test -- --show-output
cargo test后加想要测试的名称,就可以选择性的进行测试
#[cfg(test)]
#[test]
fn add1(){
println!("add1");
}
#[test]
fn add2(){
println!("add1");
}
cargo test: add1和add2都会测试
cargo test add1: 只会测试add1
cargo test add: 包含add字段的方法都会被测试
#[ignore]加在方法前可以使该方法执行cargo test时被忽略测试