如何访问 crate 的“tests”目录中的导出函数?

fad*_*bee 4 rust rust-crates

如何在创建的“tests”目录中访问我的库导出函数?

源代码/关系.rs:

#![crate_type = "lib"]

mod relations {
    pub fn foo() {
        println!("foo");
    }
}
Run Code Online (Sandbox Code Playgroud)

测试/test.rs:

use relations::foo;

#[test]
fn first() {
    foo();
}
Run Code Online (Sandbox Code Playgroud)
#![crate_type = "lib"]

mod relations {
    pub fn foo() {
        println!("foo");
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我添加了建议的extern crate relations,错误是:

use relations::foo;

#[test]
fn first() {
    foo();
}
Run Code Online (Sandbox Code Playgroud)

我想relations在这个单独的tests/test.rs文件中测试我的。我该如何解决这些use问题?

Vla*_*eev 5

你的问题是,首先,mod relations它不是公开的,所以它在板条箱之外是不可见的,其次,你没有在测试中导入你的板条箱。

如果您使用 Cargo 构建您的程序,那么 crate 名称将是您在Cargo.toml. 例如,如果Cargo.toml看起来像这样:

[package]
name = "whatever"
authors = ["Chris"]
version = "0.0.1"

[lib]
name = "relations"  # (1)
Run Code Online (Sandbox Code Playgroud)

src/lib.rs文件中包含此:

pub mod relations {  // (2); note the pub modifier
    pub fn foo() {
        println!("foo");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以把它写在tests/test.rs

extern crate relations;  // corresponds to (1)

use relations::relations;  // corresponds to (2)

#[test]
fn test() {
    relations::foo();
}
Run Code Online (Sandbox Code Playgroud)