如何对某个配置下定义的函数进行测试?

问题描述 投票:0回答:1

如何对定义了一些配置的函数进行单元测试,如下所示

struct I32Add;
impl I32Add{
    #[cfg(unstable)]
    fn add(x:i32, y:i32) -> i32{x+y}
}

#[test]
fn add_test(){
    assert_eq!(I32Add::add(1,2),3)
}

当然,测试不行。如何让它发挥作用?

unit-testing rust conditional-compilation
1个回答
0
投票

您可以将

#[cfg(unstable)]
添加到您的测试中,就像您为函数所做的那样。因此,仅当该函数被编译时,测试才会被编译:

#[cfg(unstable)]
#[test]
fn add_test() {
    assert_eq!(I32Add::add(1, 2), 3)
}

要编译和运行您的函数和测试,您必须启用

unstable
配置选项:

RUSTFLAGS="--cfg unstable" cargo test

但是,我建议您使用 cargo 功能 而不是配置选项来有条件地启用部分代码库。

struct I32Add;
impl I32Add{
    #[cfg(feature = "unstable")]
    fn add(x:i32, y:i32) -> i32{x+y}
}

#[cfg(feature = "unstable")]
#[test]
fn add_test(){
    assert_eq!(I32Add::add(1,2),3)
}

将其放在您的

cargo.toml
中:

[features]
unstable = []

然后运行它:

cargo test --features=unstable

参见:

© www.soinside.com 2019 - 2024. All rights reserved.