## test]暗含`#[cfg(test)]`吗? [英] Does `#[test]` imply `#[cfg(test)]`?

查看:249
本文介绍了## test]暗含`#[cfg(test)]`吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按惯例,Rust中的单元测试有一个单独的模块,该模块有条件地用#[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() {...}

我的问题是,#[test]是否暗示#[cfg(test)]?也就是说,如果我用#[test]而不是#[cfg(test)]标记我的测试函数,那么在非测试版本中它们是否仍然正确存在?

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?

推荐答案

我的问题是,#[test]是否暗示#[cfg(test)]?也就是说,如果我用#[test]而不是#[cfg(test)]标记我的测试函数,那么在非测试版本中它们是否仍然正确存在?

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?

是的.如果您没有使用单独的模块进行测试,则无需使用#[cfg(test)].标有#[test]的功能已从非测试版本中排除.可以很容易地验证这一点:

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
}

这篇关于## test]暗含`#[cfg(test)]`吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆