In Rust, if you want to write tests with optional features for types in your crate, you can use the cfg_attr
attribute and the #[cfg(feature = "feature_name")]
attribute to achieve this.
Here is an example:
// In lib.rs or main.rs
#[cfg(feature = "feature_name")]
pub struct MyStruct {
// ...
}
#[cfg(test)]
mod tests {
#[test]
#[cfg(feature = "feature_name")]
fn test_my_struct() {
// Write your test here
}
}
In this example, MyStruct
is only defined when feature_name
is enabled, and similarly, the test_my_struct
test is only run when feature_name
is enabled.
To run this test, you need to use the following command, where my_crate
is the name of your crate:
cargo test --features feature_name
This command enables the feature_name
feature and runs all tests, including those that depend on this feature.