【问题标题】:How to import functions from `src` for testing? [duplicate]如何从`src`导入函数进行测试? [复制]
【发布时间】:2020-09-01 10:31:04
【问题描述】:

几个小时以来,我一直试图了解如何导入函数以在 Rust 中进行测试,但没有成功。我的项目结构如下所示:

.
├── Cargo.lock
├── Cargo.toml
├── src
│  ├── main.rs
│  └── funcs
│    ├── mod.rs
│    └── hello.rs
└── tests
   └── test_hello.rs

src/funcs/mod.rs:

pub mod hello;

src/funcs/hello.rs:

pub fn hello() {
    println!("{}", "hello!");
}

src/main.rs:

mod funcs;

fn main() {
    funcs::hello::hello(); // this works
}

src/tests/test_hello.rs

mod funcs; // this import does not work!

#[test]
fn add() {
    assert_eq!(2 + 2, 4);
}

#[test]
fn hello_test() {
    assert_eq!(funcs::hello::hello(), "hello");
}

如何在src 中导入公共函数,以便在我的测试目录中使用它们?

【问题讨论】:

  • mod 定义一个模块;它不导入一个模块。使用use 导入模块。应该类似于 use crate::funcs; in test_hello.rs
  • 感谢您的帮助。当我在test_hello.rs 中使用use crate::funcs; 时,出现错误:unresolved import crate::funcs no funcs in the root。我在main.rs 中看到了mod funcs,所以我不确定这个错误是什么意思。
  • 按照 Acorn 在下方评论中的建议,将 pub mod funcs; 设置为 main.rs

标签: rust


【解决方案1】:

创建一个src/lib.rs 文件,将您的包的大部分逻辑放入一个库板条箱并在那里导出funcs 模块:

pub mod funcs;

现在,您可以随心所欲地使用库(其中包含模块)。在您的情况下,来自src/main.rstests/test_hello.rs

use <crate>::funcs;

&lt;crate&gt; 替换为与包名和根文件夹相同的库包的名称。

【讨论】:

  • 感谢您的帮助。当我将pub mod funcs;main.rs 移动到lib.rs 两者都在同一个src/ 目录中时,我现在得到file not found for module funcs 的错误。 Rust 进一步指出 help: to create the module funcs, create file "src/lib/funcs.rs".
  • 你用的是2018版吗?
  • 是的,我使用的是 2018 版。
  • 奇怪,应该可以。
  • 它应该是pub mod funcs;,因为您想从库板条箱外部访问它。我建议从头开始,首先制作一个简单的二进制+库包,然后在自己的文件中添加一个模块,然后将其移动到自己的文件夹中,等等。
【解决方案2】:

Rust crate 可以包含程序和/或库。测试只能访问库,不能访问程序(并且只能访问库的公共部分)。在您的情况下,您只有一个程序,因此您不能进行测试。为了使测试正常工作,您需要:

  • 将您的代码拆分为一个程序(在main.rs 文件中)和一个库(在lib.rs 文件中)。
  • 确保要在程序中使用的库的任何部分都是公开的。
  • 确保您要测试的库的任何部分也是公开的。
  • main.rs 和测试中,写入use foo::hello 以访问hello 函数,将foo 替换为您的库的名称。

如果要将代码拆分为模块,请在lib.rs 中使用pub mod mod_name 声明每个模块,然后在main.rs 或测试中使用use foo::mod_name; 导入它们。

【讨论】:

    【解决方案3】:

    Rust 将测试视为单独 crate 的一部分,因此您必须将 use your_crate_name::funcs; 放在测试的顶部,其中 your_crate_nameCargo.toml 中定义的主包的 crate 名称。

    【讨论】:

    • 感谢您的帮助。在我的 Cargo.toml 文件中,我的主包名为 hello。如果我将use hello::funcs; 添加到test_hello.rs 文件的顶部,我会收到错误消息:use of undeclared type or module hello;
    猜你喜欢
    • 2021-12-26
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 2012-08-13
    • 1970-01-01
    • 2019-06-04
    • 2011-06-13
    相关资源
    最近更新 更多