在Debian上进行Rust项目的单元测试,你需要遵循以下步骤:
rustc --version
cargo
命令创建一个新的项目:cargo new my_project
cd my_project
这将创建一个名为my_project
的新目录,其中包含一个简单的Rust项目。
_test
结尾。例如,如果你要测试一个名为add
的函数,你可以在同一个文件中编写一个名为test_add
的测试函数。这是一个简单的例子:// src/lib.rs
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[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);
}
}
注意#[cfg(test)]
属性,它告诉Rust编译器仅在运行测试时包含这个模块。
cargo test
命令:cargo test
这将编译项目并运行所有单元测试。测试结果将显示在终端中,包括通过的测试数量和失败的测试(如果有)。
--nocapture
选项:cargo test -- --nocapture
这将显示每个测试的详细输出,包括断言失败时的实际值和期望值。
遵循这些步骤,你可以在Debian上轻松地为你的Rust项目编写和运行单元测试。