如何测试 Rust 中的可选功能?

dfh*_*ton 9 testing unit-testing conditional-compilation rust

我有一个包,我想添加一个可选功能。我已在 Cargo.toml 中添加了适当的部分:

[features]
foo = []
Run Code Online (Sandbox Code Playgroud)

我为宏的基本功能编写了一个实验测试cfg!

#[test]
fn testing_with_foo() {
    assert!(cfg!(foo));
}
Run Code Online (Sandbox Code Playgroud)

看起来我可以在测试期间通过以下选项之一激活功能--features--all-features

(master *=) $ cargo help test
cargo-test 
Execute all unit and integration tests and build examples of a local package

USAGE:
    cargo test [OPTIONS] [TESTNAME] [-- <args>...]

OPTIONS:
    -q, --quiet                      Display one character per test instead of one line
        ...
        --features <FEATURES>...     Space-separated list of features to activate
        --all-features               Activate all available features
Run Code Online (Sandbox Code Playgroud)

不过,两者cargo test --features foo testing_with_foo都不起作用。cargo test --all-features testing_with_foo

执行此操作的正确方法是什么?

dfh*_*ton 2

解决方案是@Jmb 提出的:assert!(cfg!(feature = "foo"));。货物手册中的内容

这可以通过代码进行测试#[cfg(feature = "foo")]

允许人们确认条件编译是否有效,但不提供可以测试的布尔值。如果您想在运行时根据功能进行分支,则需要cfg!.