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

标签 unit-testing testing rust conditional-compilation

我有一个要添加可选功能的包。我在我的 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_foocargo 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/

相关文章:

generics - 特征上的链接函数

javascript - JS - 使用 IntersectionObserver 的测试代码

swift - 有没有一种传统的方法来编写等待 CloudKit 查询完成的单元测试?

python - 使用 tempfile 写入一个 csv 临时文件

ios - 在 Xcode 中,如何在运行测试时不运行某些运行脚本构建阶段?

string - 如何在单个函数中接受&str、String 和&String?

java - junit @ClassRule 的 testng 等价物是什么

java - Junit 在 Eclipse 中通过,在 Jenkins 中失败

java - 如何将参数注入(inject)TestNG类的构造函数?

rust - 同一 ARM 上不同类型的模式匹配