How to specify features for unit testing?

I have a crate library with an optional deserialize feature. I want to write tests for deserialization using some crate like serde_json, but I don't need this dependency publicly. So my Cargo.toml looks like this:

[dependencies]
serde = { version = "1.0", optional = true }

[dev-dependencies]
serde_json = "1.0"

[features]
default = []
deserialize = ["serde"]

But how do you specify that the deserialize feature be enabled when testing?

Looking at discussion in Activating features for tests/benchmarks · Issue #2911 · rust-lang/cargo · GitHub, there seems to be no dedicated way to do this. The issue thread contains some discussion of various potential workarounds. The most straightforward approach is to just run the tests using cargo test --features deserialize.

1 Like

Very sad. I will wait for improvements :melting_face:

In the meantime, you might find this helpful: cargo-all-features — Rust/Cargo add-on // Lib.rs

2 Likes

For workflows with different combinations of features, one may also use cargo-hack: for command in clippy test ; do cargo hack --feature-powerset $command ; done

2 Likes