在本文中,我们探讨了在Rust中运行测试、控制测试流、打印输出以及区分单元测试和集成测试。理解这些概念有助于简化测试执行并提高Rust项目的代码质量。
Controlling test flows 控制测试流程
So far, we have been using the cargo test
command to run our tests, but there’s a lot more we can do with tests. Let’s take a look at an example
到目前为止,我们一直在使用 cargo test
命令来运行测试,但是我们可以对测试做更多的事情。我们来看一个例子
We have two sets of command line arguments:
我们有两组命令行参数:
- For the
cargo test
command 对于cargo test
命令- Another one for the compiled test binary
另一个用于编译的测试二进制文件
These sets are separated by --
这些集合由 --
分隔
To get help with command line arguments we can always run cargo test --help
and cargo test -- --help
to print out the friendly manual for each of these set.
要获得命令行参数的帮助,我们可以运行 cargo test --help
和 cargo test -- --help
来打印出每个集合的友好手册。
Generally every test gets its own thread to run on, but if we wanted to run tests one by one (serially) we would use the — test-threads n
argument where n is the number of threads the test binary should occupy, setting it to 1 would make our tests run one by one.
一般来说,每个测试都有自己的线程来运行,但是如果我们想一个接一个地运行测试(串行地),我们会使用 — test-threads n
参数,其中n是测试二进制文件应该占用的线程数,将其设置为1将使我们的测试一个接一个地运行。
The tests we are going to run are as follows :
我们要运行的测试如下:
pub struct Guess{
value: i32,
}
impl Guess {
pub fn new(value: i32) -> Guess{
if value < 1 || value > 100 {
panic!("Value must be between 1 to 100, got {}", value);
}
Guess{ value }
}
pub fn value(&self) -> i32{
self.value
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn new_guess_120(){
Guess::new(120);
println!("Guess creation failed due to a higher value, test passed");
}
#[test]
fn new_guess_20(){
let guess = Guess::new(20);
println!("New guess created with value={}",guess.value());
}
#[test]
fn pass(){
let value: i32 = 12;
let new_guess = Guess::new(value);
println!("Expected : {}, Got : {}",value , new_guess.value());
assert_eq!(new_guess.value(),value);
}
#[test]
#[ignore]
fn fail(){