Rust单元测试实战

Rust 单元测试实战

本文基于rust edition 2021 版本,介绍Rust Test用例编写及测试用例的运行。

Rust Test编写格式

/// 配置只有在test 模式下才生效
#[cfg(test)]
mod tests {
 /// 添加Test 注解
   #[test]
   /// 定义测试函数,用来测试被测试的函数
   fn it_works() {
       let result = 2 + 2;
       assert_eq!(result, 4);
   }
}

项目目录结构

创建一个test项目

cargo new example

运行成功后,目录结构如下:
在这里插入图片描述

编写sum 函数和自定义Rectangle结构体并提供can_hold函数

fn main() {
    println!("Hello, world!");
    println!("{}",sum(2, 3));
    let rec = Rectangle{width:1,height:2};
    let rec1 = Rectangle{width:2,height:2};
    println!("{}",rec.can_hold(&rec1));
}
fn sum( a :i32,b :i32) -> i32{
    a+b
}

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

编写测试用例

#[cfg(test)]
mod test{
   use crate::sum;
   use crate::Rectangle;
   #[test]
   fn test_sum(){
       let sum = sum(2, 5);
       assert_eq!(sum, 7);
   }

   #[test]
   fn test_can_hold(){
       let larger = Rectangle {
           width: 8,
           height: 7,
       };
       let smaller = Rectangle {
           width: 5,
           height: 1,
       };

       assert!(larger.can_hold(&smaller));
   }
}

运行测试用例

cargo test

运行结果如下:
在这里插入图片描述

cargo test 常用参数

  • cargo test – --show-output
    指定输出打印信息
  • cargo test – --test-threads=2
    指定并发线程数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值