#[should_panic]
核心概念
#[should_panic] 属性标注在测试函数上,表示这个测试预期会 panic。如果测试函数 panic 了,测试通过;如果没有 panic,测试失败。这用于验证代码在非法输入或错误条件下是否正确地触发了 panic。
可以通过 #[should_panic(expected = "...")] 指定预期的 panic 消息,只有 panic 消息包含指定字符串时测试才通过。这避免了因为其他原因 panic 而误认为测试通过的情况。
pub fn divide(a: i32, b: i32) -> i32 {
if b == 0 {
panic!("除数不能为零");
}
a / b
}
pub fn get_element(slice: &[i32], index: usize) -> i32 {
if index >= slice.len() {
panic!("索引 {} 超出范围,长度为 {}", index, slice.len());
}
slice[index]
}
#[cfg(test)]
mod tests {
use super::*;
// 基本用法:只要 panic 就通过
#[test]
#[should_panic]
fn test_divide_by_zero() {
divide(10, 0);
}
// 指定预期消息:panic 消息必须包含指定字符串
#[test]
#[should_panic(expected = "除数不能为零")]
fn test_divide_by_zero_message() {
divide(10, 0);
}
// 验证索引越界
#[test]
#[should_panic(expected = "索引 5 超出范围")]
fn test_out_of_bounds() {
let data = vec![1, 2, 3];
get_element(&data, 5);
}
// 正常情况不应该 panic
#[test]
fn test_normal_divide() {
assert_eq!(divide(10, 2), 5);
}
}
fn main() {
println!("{}", divide(10, 2));
}should_panic 的行为
| 场景 | #[should_panic] | #[should_panic(expected = "msg")] |
|---|---|---|
| 函数 panic 了 | 通过 | 消息包含 "msg" 则通过 |
| 函数没有 panic | 失败 | 失败 |
| panic 消息不匹配 | 通过 | 失败 |
基本示例
// 一个带有输入验证的结构体
pub struct Temperature {
celsius: f64,
}
impl Temperature {
/// 创建温度值
///
/// # Panics
///
/// 如果温度低于绝对零度(-273.15°C)则 panic
pub fn new(celsius: f64) -> Self {
if celsius < -273.15 {
panic!("温度 {} 低于绝对零度", celsius);
}
Temperature { celsius }
}
pub fn celsius(&self) -> f64 {
self.celsius
}
pub fn fahrenheit(&self) -> f64 {
self.celsius * 9.0 / 5.0 + 32.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_normal_temperature() {
let t = Temperature::new(100.0);
assert_eq!(t.celsius(), 100.0);
}
#[test]
fn test_zero() {
let t = Temperature::new(0.0);
assert_eq!(t.fahrenheit(), 32.0);
}
#[test]
#[should_panic(expected = "低于绝对零度")]
fn test_below_absolute_zero() {
Temperature::new(-300.0);
}
#[test]
fn test_at_absolute_zero() {
// 绝对零度恰好不 panic
let t = Temperature::new(-273.15);
assert_eq!(t.celsius(), -273.15);
}
#[test]
#[should_panic]
fn test_very_cold() {
Temperature::new(-1000.0);
}
}
fn main() {
let boiling = Temperature::new(100.0);
println!("沸点: {}°C = {}°F", boiling.celsius(), boiling.fahrenheit());
}常见问题
问题一:should_panic 和 catch_unwind 哪个更好?
#[should_panic] 更简洁,适合简单的 panic 验证。catch_unwind 更灵活,可以在 panic 后继续执行其他断言。对于大多数情况,#[should_panic] 足够了。
问题二:expected 参数是精确匹配还是包含匹配?
包含匹配。panic 消息只需要包含 expected 指定的字符串即可。不需要完全相等。
问题三:should_panic 可以和 Result 返回值一起用吗?
不能。#[should_panic] 测试必须返回 (),不能返回 Result。因为 Result::Err 和 panic 是不同的错误处理机制。
问题四:panic = "abort" 模式下 should_panic 能用吗?
可以。Cargo 在测试时会自动使用 unwind 策略,即使 release profile 设置了 panic = "abort"。测试总是用 unwind。
适用场景
- 输入验证:验证非法输入是否触发 panic
- 前置条件检查:验证 assert! 和 debug_assert! 行为
- 文档一致性:确保文档中声明的 Panics 条件正确
- 边界条件:验证索引越界、溢出等行为
注意事项
expected是子字符串匹配,不是精确匹配- 不能与
Result返回值一起使用 - 测试框架总是用 unwind 模式运行 should_panic
- 建议使用
expected参数避免误匹配 - 只用于验证有意的 panic,不要用于 bug 测试
- 优先使用
Result错误处理而非 panic
总结
#[should_panic] 标注预期会 panic 的测试。函数 panic 则通过,不 panic 则失败。#[should_panic(expected = "msg")] 进一步要求 panic 消息包含指定字符串,避免因其他原因 panic 导致的误通过。常用于验证输入验证逻辑和前置条件检查。expected 是子字符串匹配。不能与 Result 返回值一起使用。测试框架总是使用 unwind 模式运行 should_panic 测试。