学习Rust的第20天:运行测试

本文详细介绍了如何在Rust中管理和控制测试流程,包括使用`cargotest`命令的不同选项,如串行运行、打印测试输出,以及区分单元测试和集成测试。还探讨了如何运行特定测试、忽略测试以及包含被忽略的测试。
摘要由CSDN通过智能技术生成

在本文中,我们探讨了在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:
我们有两组命令行参数:

  1. For the cargo test command 对于 cargo test 命令
  2. 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(){
       
  • 22
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老父亲的能量嘎嘣脆

感谢支持,共同成长

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值