7
mod simulation;

use simulation::factory::FactoryType;

works fine in main.rs, but not in a doctest inside simulation/factory.rs:

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

cargo test gives me the error

---- 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

How can I get doctests to work?

4

2 回答 2

8

当您编写文档测试时,您必须像代码的用户那样行事。鉴于这些文件:

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,然后您的所有引用都需要包含 crate 名称。doctest 是相同的,除了extern crate自动为您包含。

于 2015-09-09T14:02:40.077 回答
3

正如 huon-dbaupp 所指出的,bin crates 不能从 doc 测试中导入。

解决方案是将您的大部分代码定义为库包,并拥有一个二进制文件,该二进制文件只是围绕它的外壳。

例如,赛车手采用了这种技术。

于 2015-09-09T11:42:32.367 回答