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

只愿长相守 提交于 2019-12-13 13:25:04

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/55995061/does-test-imply-cfgtest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!