在 Rust 中,如果你想为你的 crate 中的类型编写带有可选的 feature 的测试,你可以使用cfg_attr
属性和#[cfg(feature = "feature_name")]
属性来做到这一点。
以下是一个例子:
// 在lib.rs或者main.rs中
#[cfg(feature = "feature_name")]
pub struct MyStruct {
// ...
}
#[cfg(test)]
mod tests {
#[test]
#[cfg(feature = "feature_name")]
fn test_my_struct() {
// 在这里写你的测试
}
}
在这个例子中,MyStruct
只有在feature_name
被启用时才会被定义,同样,test_my_struct
测试也只有在feature_name
被启用时才会被运行。
要运行这个测试,你需要使用以下命令,其中my_crate
是你的 crate 的名字:
cargo test --features feature_name
这个命令会启用feature_name
特性并运行所有的测试,包括依赖于这个特性的测试。