2017-02-14 21 views
3

我正在为要导出的宏编写测试。只要我将测试保存在单个文件中,测试就能正常工作,但只要我将测试模块放入单独的文件中,就会出现错误。将测试模块移动到单独的文件时未定义的宏

出口/ 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) 
    } 
} 

出口/测试/ 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

不变

出口/测试/ lib.rs

#[macro_use] 
extern crate export; 

mod my_test_mod; 

出口/测试/ 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!' 
} 

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

+0

@LukasKalbertodt这个看起来有'macro_export',并且在它被使用之前导入宏;介意将点与我的副本连接起来? – Shepmaster

+0

@Shepmaster Nevermind,我的错误。累了 ;-) –

回答

2

这里的问题是,你没有编译你认为你正在编译的东西。检查出来:

$ 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不会递归地查看测试文件的目录。

相关问题