[英]How do I access exported functions inside a crate's “tests” directory?
How do I access my libraries exported functions inside the create's "tests" directory? 如何访问创建的“ tests”目录中的库导出函数?
src/relations.rs: SRC / relations.rs:
#![crate_type = "lib"]
mod relations {
pub fn foo() {
println!("foo");
}
}
tests/test.rs: 测试/ test.rs:
use relations::foo;
#[test]
fn first() {
foo();
}
$ cargo test
Compiling relations v0.0.1 (file:///home/chris/github/relations)
/home/chris/github/relations/tests/test.rs:1:5: 1:14 error: unresolved import `relations::foo`. Maybe a missing `extern crate relations`?
/home/chris/github/relations/tests/test.rs:1 use relations::foo;
^~~~~~~~~
If I add the suggested extern crate relations
, the error is: 如果添加建议的extern crate relations
,则错误为:
/home/chris/github/relations/tests/test.rs:2:5: 2:19 error: unresolved import `relations::foo`. There is no `foo` in `relations`
/home/chris/github/relations/tests/test.rs:2 use relations::foo;
^~~~~~~~~~~~~~
I want to test my relations
in this separate tests/test.rs
file. 我想在这个单独的tests/test.rs
文件中测试我的relations
。 How can I solve these use
issues? 我该如何解决这些use
问题?
Your problem is that, first, mod relations
is not public so it is not visible outside of the crate, and second, you don't import your crate in tests. 您的问题是,首先, mod relations
不是公共的,因此在板条箱之外不可见,其次,您没有在测试中导入板条箱。
If you build your program with Cargo, then the crate name will be the one you defined in Cargo.toml
. 如果您使用Cargo构建程序,则板条箱名称将为您在Cargo.toml
定义的Cargo.toml
。 For example, if Cargo.toml
looks like this: 例如,如果Cargo.toml
看起来像这样:
[package]
name = "whatever"
authors = ["Chris"]
version = "0.0.1"
[lib]
name = "relations" # (1)
And src/lib.rs
file contains this: src/lib.rs
文件包含以下内容:
pub mod relations { // (2); note the pub modifier
pub fn foo() {
println!("foo");
}
}
Then you can write this in tests/test.rs
: 然后,您可以在tests/test.rs
编写它:
extern crate relations; // corresponds to (1)
use relations::relations; // corresponds to (2)
#[test]
fn test() {
relations::foo();
}
The solution was to specify a crate_id
at the top of src/relations.rs: 解决方案是在src / relations.rs的顶部指定一个crate_id
:
#![crate_id = "relations"]
#![crate_type = "lib"]
pub fn foo() {
println!("foo");
}
This seems to declare that all the contained code is part of a "relations" module, though I'm still not sure how this is different to the earlier mod
block. 这似乎声明所有包含的代码都是“关系”模块的一部分,尽管我仍然不确定这与早期的mod
块有何不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.