如何在单元测试中以编程方式设置target_os?

时间:2020-09-16 19:26:50

标签: unit-testing rust tdd

我尝试了以下方法:

fn get_system_extension(&self) -> String {
    if cfg!(target_os = "windows") {
        String::from(".lib")
    } else {
        String::new()
    }
}

mod test {
    #[allow(unused_imports)]
    use super::*;

    use std::env;

    #[test]
    fn get_system_extension_one() -> Result<(), CcrustyError> {
        env::set_var("CARGO_BUILD_TARGET", "linux");

        let result = get_system_extension();

        assert_eq!(String::new(), result);

        Ok(())
    }

    #[test]
    fn get_system_extension_two() -> Result<(), CcrustyError> {
        env::set_var("CARGO_CFG_UNIX", "");

        let result = get_system_extension();

        assert_eq!(String::new(), result);

        Ok(())
    }
}

根据the documentation可以在文件中进行设置,但是我不知道如何将它们动态链接到测试。

1 个答案:

答案 0 :(得分:0)

您在寻找类似的东西吗?

#[test]
    fn currect_system_extension() -> Result<(), CcrustyError> {
        let system = env::var_os("CARGO_BUILD_TARGET");
        let result = get_system_extension();

        match system => {
             "linux" => assert_eq!(String::new(), result),
             "windows" => assert_eq!(".libs".to_string(), result),
             _ => (),
        }
        Ok(())
    }

即使如此,您也必须编译此测试的两个版本以覆盖代码。看一下使用--all-targets

https://doc.rust-lang.org/cargo/commands/cargo-test.html