概述
Rust内置了单元测试的支持,这点和Golang一样,非常的棒,我超级喜欢单元测试!!!
本节课的代码还是基于之前的求公约数的案例。
之前的完整代码如下:
rust
fn gcd(mut n: u64, mut m: u64) -> u64 {
assert!(n != 0 && m != 0);
while m != 0 {
if m < n {
let t = m;
m = n;
n = t;
}
m = m % n;
}
n
}
fn main() {
let r: u64 = gcd(88, 99);
println!("{}", r);
}
添加单元测试代码
基于之前的代码,我们可以添加如下测试代码:
rust
#[test]
fn test_gcd(){
assert_eq!(gcd(14, 15), 1);
assert_eq!(gcd(2*3*5*11*17, 3*7*11*13*19), 3*11);
}
#[test]
是一个标记,将test_gcd
标记为一个测试函数,在正常编译的时候会跳过它。但是如果使用 cargo test
命令运行程序,则会自动包含并调用它。
在Rust中,因为这种机制的存在,我们可以将测试代码紧挨着函数编写,而不必单独为测试代码开辟一个新的文件。
实战:单元测试
创建项目:
bash
cargo new hello
修改代码:
bash
cd hello
vim src/main.rs
完整代码如下:
rust
fn gcd(mut n: u64, mut m: u64) -> u64 {
assert!(n != 0 && m != 0);
while m != 0 {
if m < n {
let t = m;
m = n;
n = t;
}
m %= n;
}
n
}
#[test]
fn test_gcd(){
assert_eq!(gcd(14, 15), 1);
assert_eq!(gcd(2*3*5*11*17, 3*7*11*13*19), 3*11);
}
fn main() {
let r: u64 = gcd(88, 99);
println!("{}", r);
}
执行测试:
bash
zhangdapeng@zhangdapeng:~/code/hello$ cargo test
Compiling c10_func v0.1.0 (/home/zhangdapeng/code/hello)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.34s
Running unittests src/main.rs (target/debug/deps/c10_func-7066c0fd0fc42bb9)
running 1 test
test test_gcd ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
运行代码:
bash
zhangdapeng@zhangdapeng:~/code/hello$ cargo test
Compiling c10_func v0.1.0 (/home/zhangdapeng/code/hello)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.34s
Running unittests src/main.rs (target/debug/deps/c10_func-7066c0fd0fc42bb9)
running 1 test
test test_gcd ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
代码清理:
bash
zhangdapeng@zhangdapeng:~/code/hello$ cargo clean
Removed 52 files, 14.0MiB total