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
相关推荐
Naylor19 小时前
只借不占:Rust 的引用与借用
后端·rust
对象存储与RustFS1 天前
RustFS 后台扫描器与自愈调参:五档速度、位腐检测周期与并发上限
后端·rust·开源
q平面人2 天前
【总工笔记】mindoc平板、桌面端笔记软件,发布到mindoc服务端
rust·tauri·华为平板·mindoc·总工笔记
MC皮蛋侠客2 天前
Tauri 2.x 系列(九):安全模型——Capabilities、Permissions、Scope 与 CSP
rust·tauri
Source.Liu2 天前
【Dioxus】Windows 环境下 Rust + Dioxus 安装配置笔记
windows·rust·dioxus
zLLM_Lab2 天前
不装 Python/PyTorch:8.1 MB Rust 程序在 MacBook Air M5 跑多模态大模型
rust
梦醒沉醉2 天前
std1.97.1——result模块细览
rust
Thneonl2 天前
同一资源、不同 ID:多源拓扑的 Identity Resolution
架构·rust
绍磊leo2 天前
【保姆级】dora-rs 一键安装脚本:类ros2的fishros 风格交互菜单 + 国内镜像加速,把坑都替你踩完了
rust·dora-rs
Ramble_Naylor3 天前
只借不占:Rust 的引用与借用
开发语言·rust