在Rust中,编写单元测试非常简单。首先,确保你已经安装了Rust编程语言和cargo包管理器。接下来,按照以下步骤编写单元测试:
cargo new my_project
cd my_project
src/lib.rs(对于库项目)或src/main.rs(对于可执行项目)中编写你的代码。例如,在src/lib.rs中添加以下函数:pub fn add(a: i32, b: i32) -> i32 {
a + b
}
test_开头,它们位于#[cfg(test)]模块中。例如,在src/lib.rs中添加以下测试函数:#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(1, 2), 3);
assert_eq!(add(-1, 1), 0);
assert_eq!(add(0, 0), 0);
}
}
在这个例子中,我们使用了assert_eq!宏来检查add函数的输出是否与预期相符。
cargo test
这将编译项目并运行所有测试。你应该看到类似以下的输出:
running 1 test
test tests::test_add ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.001s
这表示你的测试已成功通过。
#[cfg(test)]模块中添加更多测试函数,并使用assert_*宏来验证你的代码。这就是在Rust中编写单元测试的基本方法。你可以根据需要编写更复杂的测试,包括使用#[test]属性的自定义测试属性、使用should_panic属性测试恐慌情况等。更多关于Rust测试的信息,请参阅Rust官方文档。