Conventionally, unit tests in Rust are given a separate module, which is conditionally compiled with #[cfg(test)]
:
#[cfg(test)]
mod tests {
#[test]
fn test1() { ... }
#[test]
fn test2() { ... }
}
However, I've been using a style where tests are more inline:
pub fn func1() {...}
#[cfg(test)]
#[test]
fn test_func1() {...}
pub fn func2() {...}
#[cfg(test)]
#[test]
fn test_func2() {...}
My question is, does #[test]
imply #[cfg(test)]
? That is, if I tag my test functions with #[test]
but not #[cfg(test)]
, will they still be correctly absent in non-test builds?
My question is, does
#[test]
imply#[cfg(test)]
? That is, if I tag my test functions with#[test]
but not#[cfg(test)]
, will they still be correctly absent in non-test builds?
Yes. If you are not using a separate module for tests then you don't need to use #[cfg(test)]
. Functions marked with #[test]
are already excluded from non-test builds. This can be verified very easily:
#[test]
fn test() {}
fn main() {
test(); // error[E0425]: cannot find function `test` in this scope
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With