rust - 如何从我的测试目录中的文件访问 src 目录中的文件?

标签 rust rust-cargo

我有一个如下所示的项目布局:

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.rssrc/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/

相关文章:

javascript - wasm可以使用sysinfo依赖项吗?

struct - 在结构体的字段中使用引用时是否有任何限制?

testing - 如何只运行库和集成测试?

rust - cargo 构建失败 : could not find macro `llvm_asm` in this scope

rust - 我可以获得 Rust 链接的原生工件的完整路径吗?

rust - nixos:我的自定义包派生在 `cargo build` 上失败

rust - 为什么特质类型 `Box<dyn Error>`出现 “Sized is not implemented”错误,但 `async fn() -> Result<(), Box<dyn Error>>`有效?

rust - 我如何将 'pass down' 功能标志标记为 Cargo 中的子依赖项?

rust - Trait 函数中 &self 参数必须吗?

rust - 为什么 `cargo build`紧接着 `cargo check`重新编译了一些依赖?