Where should I put the functions of the testing utility in Rust?

I have the following code defining the path in which the generated files can be created:

fn gen_test_dir() -> tempdir::TempDir { tempdir::TempDir::new_in(Path::new("/tmp"), "filesyncer-tests").unwrap() } 

This function is defined in tests/lib.rs , which is used in tests in this file, and I would also like to use it in unit tests located in src/lib.rs

Is it possible to achieve this without compiling the utility functions into non-test binary code and without duplicate code?

+8
source share
2 answers

What I am doing is putting my unit tests with any other utilities in 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 } 
+6
source

You can import from your modules #[cfg(test)] from other modules #[cfg(test)] , therefore, for example, in main.rs or in some other module you can do something like:

 #[cfg(test)] pub mod test_util { pub fn return_two() -> usize { 2 } } 

and then from anywhere else in your project:

 #[cfg(test)] mod test { use crate::test_util::return_two; #[test] fn test_return_two() { assert_eq!(return_two(), 2); } } 
0
source

All Articles