如何在 doctest 中使用自定义模块?
How can I use a custom module inside a doctest?
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
我怎样才能让 doctests 工作?
正如 huon-dbaupp 所指出的,无法从文档测试中导入 bin crates。
解决方案是将您的大部分代码定义为一个库箱,并有一个二进制文件只是 shell 围绕它。
例如,racer 采用了这种技术。
编写文档测试时,您必须充当代码的用户。给定这些文件:
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
是自动包含的。
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
我怎样才能让 doctests 工作?
正如 huon-dbaupp 所指出的,无法从文档测试中导入 bin crates。
解决方案是将您的大部分代码定义为一个库箱,并有一个二进制文件只是 shell 围绕它。
例如,racer 采用了这种技术。
编写文档测试时,您必须充当代码的用户。给定这些文件:
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
是自动包含的。