在Rust中,单元测试是通过内置的测试框架进行的。要在Linux中进行单元测试,请按照以下步骤操作:
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_
开头,并且它们应该是pub fn
。例如,在src/lib.rs
中添加一个测试函数:#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 2), 4);
}
}
这里,我们使用#[cfg(test)]
属性来指示这个模块仅在运行测试时包含在编译中。use super::*;
语句允许我们在测试函数中使用add
函数。
cargo test
命令运行测试: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.00s
如果您想要运行特定的测试函数,可以使用-k
选项指定测试名称:
cargo test -k test_add
这就是在Linux中使用Rust进行单元测试的基本方法。您可以根据需要编写更多的测试函数,并使用cargo test
命令运行它们。