首页 > 解决方案 > 是否可以仅在测试中启用 rust 功能?

问题描述

假设我有板条箱 A、B,并且我想将helper()板条箱 A 中的测试辅助函数共享给板条箱 B,所以我使用了一个功能test-utils

#[cfg(feature="test-utils")]
pub fn helper(){

}

所以问题是由于辅助函数包含对A中敏感数据的修改,我不希望这个函数在生产中编译,例如cargo build --all-features.

有没有办法只在测试中启用此功能,并在生产中禁用它?</p>

标签: unit-testingrust

解决方案


这是Cargo要求的功能,只能使用版本 2 解析器。如果板条箱 A 具有您提到的功能,那么板条箱 BCargo.toml可能包含

[package]
name = "B"
resolver = "2"

[features]
test-utils = []

[dependencies]
A = "*"

[dev-dependencies]
A = { version = "*", features = ["test-utils"] }
B = { path = ".", features = ["test-utils"] }

这将确保两个 crate在测试时使用该test-utils功能构建。我用来跑步

cargo build --release -vv
cargo test --release -vv

并确保我真的得到了我在这两种情况下所要求的功能。


推荐阅读