如何从集成测试中调用测试辅助函数?
How to call test helper function from within integration tests?
我正在尝试弄清楚如何最好地在 Rust 中组织我的测试,我 运行 遇到了以下问题。我有一个在模块中定义的测试实用程序 (test_util
),我希望能够在我的单元测试和集成测试中使用它。
test_util
在src/lib.rs
中的定义:
#[cfg(test)]
pub mod test_util {
pub fn test_helper() {}
}
我可以从另一个模块中的单元测试访问我的辅助函数,src/some_module.rs
:
#[cfg(test)]
pub mod test {
use crate::test_util::test_helper;
#[test]
fn test_test_helper() {
test_helper();
}
}
但是,当我尝试使用集成测试中的实用程序时,如 tests/integration_test.rs
:
use my_project::test_util::test_helper;
#[test]
fn integration_test_test_helper() {
test_helper();
}
我收到以下编译器消息:
8 | use my_project::test_util::test_helper;
| ^^^^^^^^^ could not find `test_util` in `my_project`
为什么不允许从属于 相同 项目的集成测试中访问该项目的测试代码是否有充分的理由?我知道集成测试只能访问代码的 public 部分,但我认为也允许访问单元测试代码的 public 部分是有意义的。有什么解决办法?
test
功能仅在 运行 that crate 上进行测试时启用。集成测试在 crate 外部 运行,因此您无法访问 test
.
上的任何内容
在我的公司,我们有一个约定,将共享测试实用程序放在包顶层的 public test_utils
模块中。您 可以 将此模块置于您自己的功能之后,比如 integration_test
,您总是在 运行 进行这些测试时启用它,但我们目前不会为此烦恼.
我正在尝试弄清楚如何最好地在 Rust 中组织我的测试,我 运行 遇到了以下问题。我有一个在模块中定义的测试实用程序 (test_util
),我希望能够在我的单元测试和集成测试中使用它。
test_util
在src/lib.rs
中的定义:
#[cfg(test)]
pub mod test_util {
pub fn test_helper() {}
}
我可以从另一个模块中的单元测试访问我的辅助函数,src/some_module.rs
:
#[cfg(test)]
pub mod test {
use crate::test_util::test_helper;
#[test]
fn test_test_helper() {
test_helper();
}
}
但是,当我尝试使用集成测试中的实用程序时,如 tests/integration_test.rs
:
use my_project::test_util::test_helper;
#[test]
fn integration_test_test_helper() {
test_helper();
}
我收到以下编译器消息:
8 | use my_project::test_util::test_helper;
| ^^^^^^^^^ could not find `test_util` in `my_project`
为什么不允许从属于 相同 项目的集成测试中访问该项目的测试代码是否有充分的理由?我知道集成测试只能访问代码的 public 部分,但我认为也允许访问单元测试代码的 public 部分是有意义的。有什么解决办法?
test
功能仅在 运行 that crate 上进行测试时启用。集成测试在 crate 外部 运行,因此您无法访问 test
.
在我的公司,我们有一个约定,将共享测试实用程序放在包顶层的 public test_utils
模块中。您 可以 将此模块置于您自己的功能之后,比如 integration_test
,您总是在 运行 进行这些测试时启用它,但我们目前不会为此烦恼.