• Rust中的单元测试


    概述

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

    本节课的代码还是基于之前的求公约数的案例。
    之前的完整代码如下:

    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);
    }
    

    添加单元测试代码

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

    #[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中,因为这种机制的存在,我们可以将测试代码紧挨着函数编写,而不必单独为测试代码开辟一个新的文件。

    实战:单元测试

    创建项目:

    cargo new hello
    

    修改代码:

    cd hello
    vim src/main.rs
    

    完整代码如下:

    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);
    }
    

    执行测试:

    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
    
    

    运行代码:

    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
    
    

    代码清理:

    zhangdapeng@zhangdapeng:~/code/hello$ cargo clean
         Removed 52 files, 14.0MiB total
    
  • 相关阅读:
    Linux I2C(二) - I2C软硬件架构
    【scratch案例教学】scratch中秋佳节 scratch创意编程 少儿编程 边玩边学 小朋友这样贺中秋
    底层源码面试题丨深入剖析Integer缓存机制相关的问题!
    Socks5与HTTP的区别与应用场景
    Linux(Ubuntu)用户与用户组(入门必看)
    使用Everything分析和清理C盘
    GBase 8c数据类型-几何类型
    游戏找不到msvcr100dll怎么办,分享5个有效修复方法
    欧洲云巨头OVHcloud收购边缘计算专家 gridscale
    Power BI 傻瓜入门 3. 选择Power BI的版本
  • 原文地址:https://blog.csdn.net/qq_37703224/article/details/138873667