在 Rust 中,我应该在哪里放置测试实用程序函数?
问题描述:
我有以下代码定义了可以放置生成文件的路径:
I have the following code defining a path where generated files can be placed:
fn gen_test_dir() -> tempdir::TempDir {
tempdir::TempDir::new_in(Path::new("/tmp"), "filesyncer-tests").unwrap()
}
这个函数在 tests/lib.rs
中定义,用于该文件中的测试,我也想在位于 src/lib.rs 的单元测试中使用它代码>.
This function is defined in tests/lib.rs
, used in the tests in that file and I would also like to use it in the unit tests located in src/lib.rs
.
这是否可以在不将实用程序函数编译为非测试二进制文件且不复制代码的情况下实现?
Is this possible to achieve without compiling the utility functions into the non-test binary and without duplicating code?
答
我所做的是将我的单元测试与任何其他实用程序放入一个子模块中,该子模块由 #[cfg(test)]
保护:
What I do is put my unit tests with any other utilities into a submodule protected with #[cfg(test)]
:
#[cfg(test)]
mod tests { // The contents could be a separate file if it helps organisation
// Not a test, but available to tests.
fn some_utility(s: String) -> u32 {
...
}
#[test]
fn test_foo() {
assert_eq!(...);
}
// more tests
}