在Rust中,编写单元测试非常简单。Rust的包管理器和构建系统Cargo会自动识别并运行你的单元测试。下面是一些关于如何在Linux中编写Rust单元测试的基本步骤:
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
}
#[cfg(test)]属性来标记测试模块,并使用#[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);
}
}
cargo test
running 1 test
test tests::test_add ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
如果有测试失败,Cargo将显示失败的测试和错误信息。
这就是在Linux中使用Rust编写单元测试的基本方法。你可以根据需要添加更多的测试函数和模块,以确保你的代码按预期工作。