How to make a unit test for a function defined some configuration like what follows
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)
}
Of course, the test doesn't work. how to make it work?
CodePudding user response:
You can add #[cfg(unstable)]
to your test just as you've done for your function. So the test is only compiled if that function is compiled:
#[cfg(unstable)]
#[test]
fn add_test() {
assert_eq!(I32Add::add(1, 2), 3)
}
To get your function and the test to compile and run, you have to enable the unstable
config option:
RUSTFLAGS="--cfg unstable" cargo test
However, I would recommended that you use a cargo feature instead of a config option for conditionally enabling portions of your code-base.
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)
}
with this in your cargo.toml
:
[features]
unstable = []
And then run it like:
cargo test --features=unstable
See: