简体   繁体   中英

Does `#[test]` imply `#[cfg(test)]`?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM