2015-09-09 36 views
5
mod simulation; 

use simulation::factory::FactoryType; 

main.rs工作正常,但不是在裏面simulation/factory.rs一個文檔測試:如何在doctest中使用自定義模塊?

impl product_type::ProductType for FactoryType { 
    /// Lorem Ipsum 
    /// 
    /// # Examples 
    /// 
    /// ``` 
    /// use simulation::factory::FactoryType; 
    /// 
    /// ... 
    /// ``` 
    fn human_id(&self) -> &String { 
     ... 
    } 
} 

cargo test給我的錯誤

---- simulation::factory::human_id_0 stdout ---- 
    <anon>:2:9: 2:19 error: unresolved import `simulation::factory::FactoryType`. Maybe a missing `extern crate simulation`? 
<anon>:2  use simulation::factory::FactoryType; 
       ^~~~~~~~~~ 
error: aborting due to previous error 
thread 'simulation::factory::human_id_0' panicked at 'Box<Any>', /home/rustbuild/src/rust-buildbot/slave/stable-dist-rustc-linux/build/src/libsyntax/diagnostic.rs:192 

我怎樣才能得到文檔測試工作?

+1

如果你正在創建一個二進制文件(例如,如果你有'src/main.rs'而不是'src/lib.rs'),那麼你不能在doctest中使用它的函數:doc tests import他們來自一個圖書館(如果它是一個)。 – huon

+0

請求幫助時,請花時間創建[MCVE](/ help/mcve)。正如你現在所說的你的問題,我們必須做很多猜測才能確切地知道存在什麼。 – Shepmaster

回答

6

當您編寫文檔測試時,您必須充當代碼的用戶。鑑於這些文件:

的src/lib.rs

pub mod simulation { 
    pub mod factory { 
     pub struct FactoryType; 

     impl FactoryType { 
      /// ``` 
      /// use foo::simulation::factory::FactoryType; 
      /// 
      /// let f = FactoryType; 
      /// assert_eq!(42, f.human_id()) 
      /// ``` 
      pub fn human_id(&self) -> u8 { 41 } 
     } 
    } 
} 

的src/main.rs

extern crate foo; 
use foo::simulation::factory::FactoryType; 

fn main() { 
    let f = FactoryType; 
    println!("{}", f.human_id()); 
} 

一切正常。請注意,在main.rs,你必須說extern crate,那麼你所有的引用需要包括箱子名稱。 doctest是一樣的,只有extern crate自動包含給你。

3

正如huon-dbaupp指出的,bin箱不能從doc測試中導入。

解決方案是將大部分代碼定義爲庫箱,並且只有一個二進制文件,它只是一個shell。

例如,racer採用這種技術。

+0

C#也是如此,直到它們在exes中將其固定爲測試。來生鏽,刪除陷阱。 – Squirrel

相關問題