在 Rust 中,我应该在哪里放置测试实用程序函数? [英] Where should I put test utility functions in Rust?
本文介绍了在 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
}
这篇关于在 Rust 中,我应该在哪里放置测试实用程序函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文