Pur*_*reW 8 testing unit-testing rust
我有以下代码定义生成文件的路径:
fn gen_test_dir() -> tempdir::TempDir {
tempdir::TempDir::new_in(Path::new("/tmp"), "filesyncer-tests").unwrap()
}
Run Code Online (Sandbox Code Playgroud)
这个函数定义在tests/lib.rs
,在该文件的测试中使用,我也想在位于的单元测试中使用它src/lib.rs
.
如果不将实用程序功能编译成非测试二进制文件而不重复代码,是否可以实现?
我所做的是将我的单元测试与任何其他实用程序一起放入受以下保护的子模块中#[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
}
Run Code Online (Sandbox Code Playgroud)
您可以#[cfg(test)]
从其他#[cfg(test)]
模块导入您的模块,因此,例如,在main.rs
其他模块中或在其他模块中,您可以执行以下操作:
#[cfg(test)]
pub mod test_util {
pub fn return_two() -> usize { 2 }
}
Run Code Online (Sandbox Code Playgroud)
然后从项目中的任何其他地方:
#[cfg(test)]
mod test {
use crate::test_util::return_two;
#[test]
fn test_return_two() {
assert_eq!(return_two(), 2);
}
}
Run Code Online (Sandbox Code Playgroud)