我有一个如下所示的项目布局:
src/
int_rle.rs
lib.rs
tests/
test_int_rle.rs
该项目使用 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`.
我的代码:
// 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]
相关:How do I compile a multi-file crate in Rust? (如果测试文件和源文件在同一个文件夹中怎么办。)
最佳答案
文件 src/int_rle.rs
和 src/lib.rs
构成了您的库,它们一起被称为一个crate。 p>
您的测试和示例文件夹不被视为包的一部分。这很好,因为当有人使用您的库时,他们不需要您的测试,他们只需要您的库。
您可以通过将行 extern crate minimal_example_test_directories;
添加到 tests/test_int_rle.rs
的顶部来解决您的问题。
您可以在本书 here 中阅读更多关于 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] };
}
}
关于rust - 如何从我的测试目录中的文件访问 src 目录中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40305337/