#[test] 是Rust中的注解属性,用于编译环境的注解,类似 java 中的 annotation 和 C# 中的 attribute 。
通过#[test]注解,可以在运行时添加-test 参数进行单元测试。
一、基本使用
1
2
3
4
5 1$cargo new attribute_test --bin
2$cd attribute_test
3$vi src/main.rs
4
5
main.rs 代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 1fn main(){
2}
3
4macro_rules! say_hello{
5 ()=>(
6 println!("Hello");
7 )
8}
9
10#[test]
11fn test_say_hello(){
12 say_hello!();
13}
14
15
运行
1
2
3 1$cargo test
2
3
结果
1
2
3
4
5
6
7 1Running target/debug/attribute_test-431700a6ad4b39fd
2
3running 1 test
4test test_say_hello ... ok
5
6test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
7
二、增加一个 say( ) 功能函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 1fn main(){
2
3}
4
5macro_rules! say_hello{
6 ()=>(
7 println!("Hello");
8 )
9}
10
11#[test]
12fn test_say_hello(){
13 say();
14}
15
16fn say(){
17 say_hello!();
18}
19
20
say( )功能函数在 test_say_hello( )下面,
✅ 可以正常调用。
说明,在同一个文件中功能函数之间的顺序没有关系。
三、将宏放到功能函数后面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 1fn main(){
2
3}
4
5#[test]
6fn test_say_hello(){
7 say();
8}
9
10fn say(){
11 say_hello!();
12}
13
14macro_rules! say_hello{
15 ()=>(
16 println!("Hello");
17 )
18}
19
执行,提示
1
2
3 1error: macro undefined: 'say_hello!'
2
3
❌ 不能编译!
宏定义要出现在使用的功能函数前面!
通常将所有的宏定义在单独的 模块/文件 中,然后通过 #[macro_use] 引入当前使用域。
四、使用宏模块 (macro module)
创建宏模块
1
2
3 1$vi macros.rs
2
3
模块内容
1
2
3
4
5
6 1macro_rules! say_hello{
2 ()=>(
3 println!("Hello");
4 )
5}
6
修改主文件
1
2
3 1$vi main.rs
2
3
文件内容,文中增加#[macro_use]导入macros宏模块
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 1#[macro_use]
2mod macros;
3
4
5fn main(){
6 say();
7}
8
9
10#[test]
11fn test_say_hello(){
12 say();
13}
14
15
16fn say(){
17 say_hello!();
18}
19
1
2
3 1$cargo run
2
3
1
2
3 1Running `target/debug/attribute_test`
2Hello
3
✅ 通过!
1
2
3 1$cargo test
2
3
1
2
3
4
5
6
7 1Running target/debug/attribute_test-431700a6ad4b39fd
2
3running 1 test
4test test_say_hello ... ok
5
6test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
7
✅ 通过!