Rust中的单元测试

概述

Rust内置了单元测试的支持,这点和Golang一样,非常的棒,我超级喜欢单元测试!!!

本节课的代码还是基于之前的求公约数的案例。

之前的完整代码如下:

rust 复制代码
fn gcd(mut n: u64, mut m: u64) -> u64 {
    assert!(n != 0 && m != 0);
    while m != 0 {
        if m < n {
            let t = m;
            m = n;
            n = t;
        }
        m = m % n;
    }
    n
}

fn main() {
    let r: u64 = gcd(88, 99);
    println!("{}", r);
}

添加单元测试代码

基于之前的代码,我们可以添加如下测试代码:

rust 复制代码
#[test]
fn test_gcd(){
	assert_eq!(gcd(14, 15), 1);
	assert_eq!(gcd(2*3*5*11*17, 3*7*11*13*19), 3*11);
}

#[test]是一个标记,将test_gcd标记为一个测试函数,在正常编译的时候会跳过它。但是如果使用 cargo test命令运行程序,则会自动包含并调用它。

在Rust中,因为这种机制的存在,我们可以将测试代码紧挨着函数编写,而不必单独为测试代码开辟一个新的文件。

实战:单元测试

创建项目:

bash 复制代码
cargo new hello

修改代码:

bash 复制代码
cd hello
vim src/main.rs

完整代码如下:

rust 复制代码
fn gcd(mut n: u64, mut m: u64) -> u64 {
    assert!(n != 0 && m != 0);
    while m != 0 {
        if m < n {
            let t = m;
            m = n;
            n = t;
        }
        m %= n;
    }
    n
}

#[test]
fn test_gcd(){
    assert_eq!(gcd(14, 15), 1);
    assert_eq!(gcd(2*3*5*11*17, 3*7*11*13*19), 3*11);
}

fn main() {
    let r: u64 = gcd(88, 99);
    println!("{}", r);
}

执行测试:

bash 复制代码
zhangdapeng@zhangdapeng:~/code/hello$ cargo test
   Compiling c10_func v0.1.0 (/home/zhangdapeng/code/hello)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.34s
     Running unittests src/main.rs (target/debug/deps/c10_func-7066c0fd0fc42bb9)

running 1 test
test test_gcd ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

运行代码:

bash 复制代码
zhangdapeng@zhangdapeng:~/code/hello$ cargo test
   Compiling c10_func v0.1.0 (/home/zhangdapeng/code/hello)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.34s
     Running unittests src/main.rs (target/debug/deps/c10_func-7066c0fd0fc42bb9)

running 1 test
test test_gcd ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

代码清理:

bash 复制代码
zhangdapeng@zhangdapeng:~/code/hello$ cargo clean
     Removed 52 files, 14.0MiB total
相关推荐
superman超哥16 分钟前
Rust Cargo Build 编译流程:从源码到二进制的完整旅程
开发语言·后端·rust·编译流程·cargo build·从源码到二进制
Yuer20251 小时前
为什么要用rust做算子执行引擎
人工智能·算法·数据挖掘·rust
古城小栈2 小时前
Rust语言:优势解析与擅长领域深度探索
开发语言·后端·rust
superman超哥2 小时前
Rust Cargo.toml 配置文件详解:项目管理的核心枢纽
开发语言·后端·rust·rust cargo.toml·cargo.toml配置文件
superman超哥3 小时前
Rust 注释与文档注释:代码即文档的工程实践
开发语言·算法·rust·工程实践·rust注释与文档注释·代码即文档
superman超哥3 小时前
Rust 依赖管理与版本控制:Cargo 生态的精妙设计
开发语言·后端·rust·rust依赖管理·rust版本控制·cargo生态
superman超哥4 小时前
Rust 泛型参数的使用:零成本抽象的类型级编程
开发语言·后端·rust·零成本抽象·rust泛型参数·类型级编程
jump_jump4 小时前
Grit:代码重构利器
性能优化·rust·代码规范
Cherry的跨界思维13 小时前
【AI测试全栈:质量模型】4、新AI测试金字塔:从单元到社会的四层测试策略落地指南
人工智能·单元测试·集成测试·ai测试·全栈ai·全栈ai测试·社会测试
布列瑟农的星空13 小时前
Playwright使用体验
前端·单元测试