是否可以仅在测试中启用 Rust 功能?

nam*_*exp 10 unit-testing rust

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

\n
#[cfg(feature="test-utils")]\npub fn helper(){\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

有没有办法仅在测试中启用此功能,并在生产\xef\xbc\x9f 中禁用它

\n

la *_*eur 10

这是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"] }
Run Code Online (Sandbox Code Playgroud)

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

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

[features]
test-utils = []

[dependencies]
A = "*"

[dev-dependencies]
A = { version = "*", features = ["test-utils"] }
B = { path = ".", features = ["test-utils"] }
Run Code Online (Sandbox Code Playgroud)

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