2017-02-14 48 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不會遞歸地查看測試文件的目錄。

相關問題