rust成长之路-测试案例

一.标注方法为测试方法

使用#[test]标注一个方法使其成为测试方法,例:

#[cfg(test)]
pub mod test_module {
    
    #[test]
    fn test() {
        let x = 2 + 2;
        assert_eq!(x, 4);
    }
}

该方法为测试方法,assert_eq测试x的值是否等于4.

运行使用cargo test,控制台打印测试案例成功数和失败数等信息。

二.使用panic!抛出异常使测试案例失败

#[cfg(test)]
pub mod test_module {
    
    #[test]
    fn panic_error() {
        panic!("error");
    }
}

三.使用assert!、assert_eq!、assert_ne! 宏

#[cfg(test)]
pub mod test_module {
    #[test]
    fn success() {
        let x = 2 + 2;
        assert!(x == 4);
    }

    #[test]
    fn eq() {
        let x = 2 + 2;
        // 等于
        assert_eq!(x, 4);
    }

    #[test]
    fn ne() {
        let x = 2;
        // 不等于
        assert_ne!(x, 4);
    }
}

四.添加自定义错误信息

#[cfg(test)]
pub mod test_module {
    #[test]
    fn eq() {
        let x = 2 + 2;
        assert_eq!(x, 2, "测试x是否等于2,x当前值 {}", x);
    }
}

五.测试是否抛出异常时,可使用#[should_panic]

#[cfg(test)]
pub mod test_module {
    #[test]
    #[should_panic]
    fn eq() {
        let x = 2 + 2;
        assert_eq!(x, 2, "测试x是否等于2,x当前值 {}", x);
    }
}

作用为如果方法抛出异常,则测试案例通过,反之不通过。

5.1 定制期望的异常信息

有时只使用#[should_panic]只能知道该方法是否异常,并不知道是否是我们期望的异常,因此可以定制我们期望的异常信息时,案例通过。

#[cfg(test)]
pub mod test_module {
    #[test]
    #[should_panic(expected = "测试期望异常")]
    fn eq() {
        let x = 2 + 2;
        assert_eq!(x, 2, "测试x是否等于2,x当前值 {}", x);
    }
}

#[cfg(test)]
pub mod test_module {
    #[test]
    // 期望信息为异常的子串就可以
    #[should_panic(expected = "测试x是否等于2")]
    fn eq() {
        let x = 2 + 2;
        assert_eq!(x, 2, "测试x是否等于2,x当前值 {}", x);
    }
}

六. 测试案例返回Result<T, E>

#[cfg(test)]
pub mod test_module {
    #[test]
    fn result() -> Result<(), String> {
        if 2 + 2 == 5 {
            // 案例通过
            Ok(())
        } else {
            // 案例不通过
            Err(String::from("two plus two does not equal four"))
        }
    }
}

使用Result<T, E>无法配合#[should_panic]使用

#[cfg(test)]
pub mod test_module {
    #[test]
    #[should_panic]
    // 无法通过编译,should_panic要求无返回值
    // 但是可以使用assert!宏
    fn result() -> Result<(), String> {
        if 2 + 2 == 5 {
            Ok(())
        } else {
            Err(String::from("two plus two does not equal four"))
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值