Rust 1.7.0 使用#[test]做单元测试

#[test] 是Rust中的注解属性,用于编译环境的注解,类似 java 中的 annotation 和 C# 中的 attribute 。
通过#[test]注解,可以在运行时添加-test 参数进行单元测试。

一、基本使用
$cargo new attribute_test --bin
$cd attribute_test
$vi src/main.rs

main.rs 代码如下:

fn main(){
}

macro_rules! say_hello{
   ()=>(
       println!("Hello");
   )
}

#[test]
fn test_say_hello(){
  say_hello!();
}

运行

$cargo test

结果

Running target/debug/attribute_test-431700a6ad4b39fd

running 1 test
test test_say_hello ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
二、增加一个 say( ) 功能函数
fn main(){

}

macro_rules! say_hello{
   ()=>(
       println!("Hello");
   )
}

#[test]
fn test_say_hello(){
  say();
}

fn say(){
  say_hello!();
}

say( )功能函数在 test_say_hello( )下面,
✅ 可以正常调用。
说明,在同一个文件中功能函数之间的顺序没有关系。

三、将宏放到功能函数后面
fn main(){

}

#[test]
fn test_say_hello(){
  say();
}

fn say(){
  say_hello!();
}

macro_rules! say_hello{
   ()=>(
       println!("Hello");
   )
}

执行,提示

error: macro undefined: 'say_hello!'

❌ 不能编译!

宏定义要出现在使用的功能函数前面!

通常将所有的宏定义在单独的 模块/文件 中,然后通过 #[macro_use] 引入当前使用域。

四、使用宏模块 (macro module)

创建宏模块

$vi macros.rs

模块内容

macro_rules! say_hello{
   ()=>(
       println!("Hello");
   )
}

修改主文件

$vi main.rs

文件内容,文中增加#[macro_use]导入macros宏模块

#[macro_use]
mod macros;


fn main(){
 say();
}


#[test]
fn test_say_hello(){
  say();
}


fn say(){
  say_hello!();
}
$cargo run
Running `target/debug/attribute_test`
Hello

✅ 通过!

$cargo test
Running target/debug/attribute_test-431700a6ad4b39fd

running 1 test
test test_say_hello ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

✅ 通过!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值