Where should I put test utility functions in Rust?

前端 未结 2 453
刺人心
刺人心 2021-01-02 06:24

I have the following code defining a path where generated files can be placed:

fn gen_test_dir() -> tempdir::TempDir {                                             


        
相关标签:
2条回答
  • 2021-01-02 06:50

    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
    }
    
    0 讨论(0)
  • 2021-01-02 06:53

    You can import from your #[cfg(test)] modules from other #[cfg(test)] modules, so, 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 讨论(0)
提交回复
热议问题