【问题标题】:How can I use a custom module inside a doctest?如何在 doctest 中使用自定义模块?
【发布时间】:2015-09-09 07:23:04
【问题描述】:
mod simulation;

use simulation::factory::FactoryType;

main.rs 中工作正常,但在simulation/factory.rs 内的文档测试中却不行:

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

如何让 doctest 工作?

【问题讨论】:

  • 如果你正在创建一个二进制文件(例如,如果一个有 src/main.rs 而不是 src/lib.rs)那么你不能在 doctest 中使用它的函数:doc tests import the crate they' re from 作为一个库(如果它是一个)。
  • 请在寻求帮助时花时间创建MCVE。正如您目前所说的那样,我们必须进行大量猜测才能确切知道存在什么。

标签: rust rust-cargo


【解决方案1】:

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

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());
}

一切正常。请注意,在 ma​​in.rs 中,您必须说 extern crate,然后您的所有引用都需要包含 crate 名称。 doctest 是一样的,除了 extern crate 会自动包含在内。

【讨论】:

    【解决方案2】:

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

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

    例如,racer 采用了这种技术。

    【讨论】:

    • C# 也是如此,直到他们为 exe 中的测试修复了它。来吧生锈,消除陷阱。
    猜你喜欢
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多