繁体   English   中英

我应该在Rust中放置测试实用程序功能?

[英]Where should I put test utility functions in Rust?

我有以下代码定义生成文件的路径:

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

这个函数在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
}

您可以从导入#[cfg(test)]从其它模块#[cfg(test)]模块,因此,例如,在main.rs或以其他模块,你可以这样做:

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

然后从项目的其他任何地方:

#[cfg(test)]
mod test {
    use crate::test_util::return_two;

    #[test]
    fn test_return_two() {
        assert_eq!(return_two(), 2);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM