如何从我的测试目录中的文件访问 src 目录中的文件? [英] How do I access files in the src directory from files in my tests directory?

查看:31
本文介绍了如何从我的测试目录中的文件访问 src 目录中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a project layout that looks like the following:

src/
    int_rle.rs
    lib.rs
tests/
    test_int_rle.rs

项目使用 cargo build 编译,但我无法使用 cargo test 运行测试.我收到错误

The project compiles with cargo build, but I am unable to run the test with cargo test. I get the error

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]

相关:如何编译多Rust 中的文件箱?(如果测试和源文件在同一个文件夹中,如何做.)

Related: How do I compile a multi-file crate in Rust? (how to do it if the test and source files are in the same folder.)

推荐答案

src/int_rle.rssrc/lib.rs 文件构成了你的库,并一起被称为板条箱.

The files src/int_rle.rs and src/lib.rs form your library, and together are called a crate.

您的测试和示例文件夹不被视为板条箱的一部分.这很好,因为当有人使用您的库时,他们不需要您的测试,他们只需要您的库.

Your tests and examples folders are not considered part of the crate. This is good, because when someone uses your library, they don't need your tests, they just need your library.

您可以通过在 tests/test_int_rle.rs 顶部添加行 extern crate minimum_example_test_directories; 来解决您的问题.

You can fix your issue by adding the line extern crate minimal_example_test_directories; to the top of tests/test_int_rle.rs.

您可以在书中阅读有关 Rust 的 crate 和模块结构的更多信息,这里.

You can read more about Rust's crate and module structure in the book, here.

这应该是您的测试文件的工作版本:

This should be a working version of your test file:

// 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] };
    }
}

这篇关于如何从我的测试目录中的文件访问 src 目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆