测试模块
单元测试通常会放在嵌套模块中(在 Playground 上运行测试):
fn helper(a: &str, b: &str) -> String { format!("{a} {b}") } pub fn main() { println!("{}", helper("Hello", "World")); } #[cfg(test)] mod tests { use super::*; #[test] fn test_helper() { assert_eq!(helper("foo", "bar"), "foo bar"); } }
- 这样一来,您可以对专用帮助程序进行单元测试。
- 仅当您运行
cargo test
时,#[cfg(test)]
属性才有效。