testing - 将测试模块移动到单独的文件时未定义宏

标签 testing macros rust

我正在为要导出的宏编写测试。只要我将测试保存在一个文件中,该测试就可以正常工作,但是一旦我将测试模块放在一个单独的文件中,我就会收到错误消息。

导出/src/lib.rs

pub mod my_mod {
    #[macro_export]
    macro_rules! my_macro {
        ( $x:expr ) => { $x + 1 };
    }

    pub fn my_func(x: isize) -> isize {
        my_macro!(x)
    }
}

export/tests/lib.rs

#[macro_use]
extern crate export;

mod my_test_mod {
    use export::my_mod;

    #[test]
    fn test_func() {
        assert_eq!(my_mod::my_func(1), 2);
    }

    #[test]
    fn test_macro() {
        assert_eq!(my_macro!(1), 2);
    }
}

运行 cargo test 表示两个测试都通过了。如果我将 my_test_mod 提取到一个文件,它将不再编译。

导出/src/lib.rs

不变

export/tests/lib.rs

#[macro_use]
extern crate export;

mod my_test_mod;

export/tests/my_test_mod.rs

use export::my_mod;

#[test]
fn test_func() {
    assert_eq!(my_mod::my_func(1), 2);
}

#[test]
fn test_macro() {
    assert_eq!(my_macro!(1), 2); // error: macro undefined: 'my_macro!'
}

这给我一个宏未定义的错误。

最佳答案

这里的问题是您没有编译您认为正在编译的东西。检查一下:

$ cargo test --verbose
   Compiling export v0.1.0 (file:///private/tmp/export)
     Running `rustc --crate-name my_test_mod tests/my_test_mod.rs ...`

当您运行 cargo test 时,它假定每个 .rs 文件都是要运行的测试。它不知道 my_test_mod.rs 应该只作为另一个测试的一部分进行编译!

最简单的解决方案是将您的模块移动到另一个有效的模块位置,在一个单独的目录中:tests/my_test_mod/mod.rs。 Cargo 不会递归地在目录中查找测试文件。

关于testing - 将测试模块移动到单独的文件时未定义宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42215714/

相关文章:

testing - 白盒测试失败但黑盒测试成功的示例,反之亦然?

使用宏的任意成员变量的c++类生成

python - 不确定哪些测试用例未通过我的代码

c - 预处理器 : Concatenate string to each argument in __VA_ARGS__

macros - 如果宏是在模块中定义的,我该如何正确编写宏文档?

rust - 你如何记录函数参数?

rust - 当其中一个字符串似乎超出范围时,为什么这段带有字符串文字的代码会编译?

rust - 如何在不将代码拆分成单独的函数的情况下为SPECS框架编写单元测试?

Angular 2/4 - 如何测试指令@Input 值?

java - 如何在测试中加载 spring HTTPInvoker 到 jetty?