一、语法
1. 基本测试结构, 测试代码通常写在#[cfg(test)]模块中,使用#[test]标记测试函数
#[cfg(test)]
mod tests {
user super::*; // 引入外层模块内容
#[test]
fn test_basic() {
assert!(true);
}
}
2. 断言
- assert! 验证是否为真
- assert_eq! 是否相等
- assert_ne! 是否不相等
- matches! 模式匹配
assert!(matches!(err, ParseError::Invalid))
二、测试返回值
- 默认无返回值,即返回()
- 允许在测试中使用?操作符,返回Result类型
#[test]
fn test_file() -> Result<(), std::io::Error> {
let content = std::fs::read_to_string("test.txt")?;
assert!(content.contains("data"));
Ok(())
}
三、异常测试
- panic
使用#[should_panic]属性标记预期崩溃的测试
#[test]
#[should_panic(expected = "除数不能为零")] // 可选验证错误消息
fn test_divide_by_zero() {
divide(10, 0);
}
- 严重特定错误类型
#[test]
fn test_invalid_input() {
let result = parse("abc");
assert!(matches!(result, Err(ParseError::InvalidFromat));
}
四、测试覆盖率优化
- 条件编译测试代码
#[cfg(test)]
fn debug_helper() {
// 测试专用辅助函数 仅在测试时编译调试代码:
}
- 忽略测试
#[test]
#[ignore = "需要数据库连接"]
fn test_database() {
// 耗时/依赖外部资源的测试
}