unit-testing - 如何测试 Rust 中的可选功能?
问题描述
我有一个想要添加可选功能的包。我在 Cargo.toml 中添加了适当的部分:
[features]
foo = []
cfg!
我为宏的基本功能写了一个实验测试:
#[test]
fn testing_with_foo() {
assert!(cfg!(foo));
}
看起来我可以通过以下任一选项--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
但是,既不工作cargo test --features foo testing_with_foo
也不cargo test --all-features testing_with_foo
工作。
这样做的正确方法是什么?
解决方案
解决方案是@Jmb 提出的:assert!(cfg!(feature = "foo"));
. 货物手册中的内容
这可以通过
#[cfg(feature = "foo")]
.
允许人们确认条件编译有效,但不提供可以测试的布尔值。如果要在运行时基于特性进行分支,则需要cfg!
.