在Rust中测试就是一个函数,它用于验证非测试代码的功能是否和预期一致。
测试函数体(通常)执行的三个操作:
测试函数需要使用test属性(attribute)进行标注:
使用cargo test命令运行所有测试函数。Rust会构建一个Test Runner可执行文件,它会运行所有标注了test的函数,并报告运行是否成功。
当使用了cargo创建了library项目的时候,会生成一个test module,里面有一个test函数。我们可以添加任意数量的test module或函数。
> cargo new adder --lib Created library `adder` package
打开新建的项目,运行命令cargo test:
> cargo test Compiling adder v0.1.0 (E:\Projects\Rust\adder) Finished test [unoptimized + debuginfo] target(s) in 0.36s Running unittests (target\debug\deps\adder-b72abb8ec5bd653b.exe)running 1 testtest tests::it_works ... oktest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests adderrunning 0 teststest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
测试函数一旦触发了panic就表示失败。每一个测试都运行在一个新的线程。当主线程监测到某个测试线程panic了,该测试就被标记为失败。例:
#[cfg(test)]mod tests { #[test] fn it_works() { let result = 2 + 2; assert_eq!(result, 4); } #[test] fn another_test() { let result = 2 + 2; assert_eq!(result, 5); }}
执行cargo test,输出:
> cargo test Finished test [unoptimized + debuginfo] target(s) in 0.00s Running unittests (target\debug\deps\adder-b72abb8ec5bd653b.exe)running 2 teststest tests::it_works ... oktest tests::another_test ... FAILEDfailures:---- tests::another_test stdout ----thread 'tests::another_test' panicked at 'assertion failed: `(left == right)` left: `4`, right: `5`', src\lib.rs:12:9note: run with `RUST_BACKTRACE=1` environment variable to display a backtracefailures: tests::another_testtest result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
联系客服