在 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
特性並運行所有的測試,包括依賴於這個特性的測試。