我有一个项目布局,如下所示:
src/
int_rle.rs
lib.rs
tests/
test_int_rle.rs
Run Code Online (Sandbox Code Playgroud)
该项目编译cargo build,但我无法运行测试cargo test.我收到了错误
error[E0432]: unresolved import `int_rle`. There is no `int_rle` in the crate root
--> tests/test_int_rle.rs:1:5
|
1 | use int_rle;
| ^^^^^^^
error[E0433]: failed to resolve. Use of undeclared type or module `int_rle`
--> tests/test_int_rle.rs:7:9
|
7 | int_rle::IntRle { values: vec![1, 2, 3] }
| ^^^^^^^^^^^^^^^ Use of undeclared type or module `int_rle`
error: aborting due to 2 previous errors
error: Could not compile `minimal_example_test_directories`.
Run Code Online (Sandbox Code Playgroud)
我的代码:
// src/lib.rs
pub mod int_rle;
// src/int_rle.rs
#[derive(Debug, PartialEq)]
pub struct IntRle {
pub values: Vec<i32>,
}
// tests/test_int_rle.rs
use int_rle;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
int_rle::IntRle { values: vec![1, 2, 3] }
}
}
// Cargo.toml
[package]
name = "minimal_example_test_directories"
version = "0.1.0"
authors = ["Johann Gambolputty de von Ausfern ... von Hautkopft of Ulm"]
[dependencies]
Run Code Online (Sandbox Code Playgroud)
相关:如何在Rust中编译多文件包?(如果测试和源文件位于同一文件夹中,该怎么做.)
文件src/int_rle.rs和src/lib.rs形成你的库,一起被称为一个箱子.
您的测试和示例文件夹不被视为包的一部分.这很好,因为当有人使用你的库时,他们不需要你的测试,他们只需要你的库.
您可以通过将行添加extern crate minimal_example_test_directories;到顶部来解决您的问题tests/test_int_rle.rs.
您可以在这里阅读书中有关Rust的箱子和模块结构的更多信息.
这应该是您的测试文件的工作版本:
// tests/test_int_rle.rs
extern crate minimal_example_test_directories;
pub use minimal_example_test_directories::int_rle;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
super::int_rle::IntRle { values: vec![1, 2, 3] };
}
}
Run Code Online (Sandbox Code Playgroud)