一.标注方法为测试方法
使用#[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"))
}
}
}