pubstructGuess {
value: i32,
}
implGuess {
pubfnnew(value: i32) -> Guess {
if value < 1 || value > 100 {
panic!("Guess value must be between 1 and 100, got {}.", value);
}
Guess { value }
}
}
#[cfg(test)]mod tests {
use super::*;
#[test]#[should_panic]fngreater_than_100() {
Guess::new(200);
}
}
rust
上面是一个简单的猜数字游戏,Guess 结构体的 new 方法在传入的值不在 [1,100] 之间时,会直接 panic,而在测试函数 greater_than_100 中,我们传入的值 200 显然没有落入该区间,因此 new 方法会直接 panic,为了测试这个预期的 panic 行为,我们使用 #[should_panic] 对其进行了标注。
// --snip--implGuess {
pubfnnew(value: i32) -> Guess {
if value < 1 {
panic!(
"Guess value must be greater than or equal to 1, got {}.",
value
);
} elseif value > 100 {
panic!(
"Guess value must be less than or equal to 100, got {}.",
value
);
}
Guess { value }
}
}
#[cfg(test)]mod tests {
use super::*;
#[test]#[should_panic(expected = "Guess value must be less than or equal to 100")]fngreater_than_100() {
Guess::new(200);
}
}
rust
使用 Result
当测试函数的返回 Result 时,若发生错误,测试也将失败:
#[cfg(test)]mod tests {
#[test]fnit_works() ->Result<(), String> {
if2 + 2 == 3 {
Ok(())
} else {
Err(String::from("two plus two does not equal four"))
}
}
}
rust
---- tests::it_works stdout ----
Error: "two plus two does not equal four"
failures:
tests::it_works
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
log
传递命令行参数
使用cargo test --help可以查看帮助:
$ cargo test --help
Execute all unit and integration tests and build examples of a local package
Usage: cargo.exe test [OPTIONS] [TESTNAME] [-- [args]...]
$ cargo test one_hundred
running 1 testtest tests::one_hundred ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.00s
bash
默认情况下只会测试 lib.rs 中的内容,在这里就是tests模块。
但是只能指定一个函数,无法指定多个,例如下面的命令:
cargo test one_hundred,add_two_and_two
cargo test one_hundred add_two_and_two
bash
这两种方式统统不行,此时就需要使用名称过滤的方式来实现了。
通过名称来过滤测试
可以通过指定部分名称的方式来过滤运行相应的测试:
$ cargo test add
running 2 tests
test tests::add_three_and_two ... ok
test tests::add_two_and_two ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s
bash
实际上只要函数名包含我们指定的字符串就会被执行:
$ cargo test and
running 2 tests
test tests::add_two_and_two ... ok
test tests::add_three_and_two ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in0.00s