【问题标题】:Does `#[test]` imply `#[cfg(test)]`?`#[test]` 是否暗示 `#[cfg(test)]`?
【发布时间】:2019-09-23 11:46:59
【问题描述】:

按照惯例,Rust 中的单元测试被赋予一个单独的模块,该模块使用#[cfg(test)] 进行条件编译:

#[cfg(test)]
mod tests {
    #[test]
    fn test1() { ... }

    #[test]
    fn test2() { ... }
}

但是,我一直在使用一种更内联测试的样式:

pub fn func1() {...}

#[cfg(test)]
#[test]
fn test_func1() {...}

pub fn func2() {...}

#[cfg(test)]
#[test]
fn test_func2() {...}

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

【问题讨论】:

标签: unit-testing testing rust attributes visibility


【解决方案1】:

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

是的。如果您没有使用单独的模块进行测试,则不需要使用#[cfg(test)]。标有#[test] 的函数已从非测试版本中排除。这很容易验证:

#[test]
fn test() {}

fn main() {
    test(); // error[E0425]: cannot find function `test` in this scope
}

【讨论】:

  • 我发现,在实践中,我创建了一些辅助函数和类型来彻底测试我的代码。这些受益于条件编译的嵌套test 模块。
  • @Shepmaster 它也适用于模拟 std 库中的类型和函数,例如 Instant,否则很难在测试中使用。
  • 我不知道这对任何人是否有用,但test this is with compile_error!的另一种方式。
  • @Shepmaster 用于我使用测试模块的那种东西(或者,更常见的是,一个完全独立的tests 目录),但对于不需要 doctest 的快速内联内容,我已经发现我真的很喜欢 item-test-item-test 模式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
相关资源
最近更新 更多