#[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
✅ 通过!