我有一个要添加可选功能的包。我在我的 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"));
。 Cargo Book 中的内容
This can be tested in code via
#[cfg(feature = "foo")]
.
允许确认条件编译是否有效,但不提供可以测试的 bool 值。如果你想在运行时根据特性进行分支,你需要cfg!
。
关于unit-testing - 如何测试 Rust 中的可选功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58906379/