如何對定義了一些配置的函式進行單元測驗,如下所示
struct I32Add;
impl I32Add{
#[cfg(unstable)]
fn add(x:i32, y:i32) -> i32{x y}
}
#[test]
fn add_test(){
assert_eq!(I32Add::add(1,2),3)
}
當然,測驗不起作用。如何使它作業?
uj5u.com熱心網友回復:
您可以#[cfg(unstable)]像為您的函式所做的那樣添加到您的測驗中。因此,只有在編譯該函式時才會編譯測驗:
#[cfg(unstable)]
#[test]
fn add_test() {
assert_eq!(I32Add::add(1, 2), 3)
}
為了讓您的功能和測驗編譯和運行,您必須啟用的unstable配置選項:
RUSTFLAGS="--cfg unstable" cargo test
但是,我建議您使用貨物功能而不是配置選項來有條件地啟用部分代碼庫。
struct I32Add;
impl I32Add{
#[cfg(feature = "unstable")]
fn add(x:i32, y:i32) -> i32{x y}
}
#[cfg(feature = "unstable")]
#[test]
fn add_test(){
assert_eq!(I32Add::add(1,2),3)
}
在你的cargo.toml:
[features]
unstable = []
然后像這樣運行它:
cargo test --features=unstable
看:
- 如何設定 cfg 選項以有條件地編譯?
- 我如何在 `cfg` 和 Cargo 中使用條件編譯?
- 是否可以在 Rust 中撰寫測驗,使其不在特定作業系統上運行?
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/385169.html
