You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Rust的#[should_panic(expected = ...)]精确匹配panic消息

Rust测试中实现panic消息完全匹配的方法

默认情况下,#[should_panic(expected = "...")]是包含匹配——只要panic消息里有指定的字符串就会通过测试,不管前后有没有额外字符。要实现完全匹配,有两种简单方法:

方法一:手动捕获panic并断言完全相等

直接用std::panic::catch_unwind捕获panic,提取消息后用assert_eq!做严格的完全匹配校验:

#[test]
fn foo_test() {
    // 捕获foo()执行时的panic
    let panic_result = std::panic::catch_unwind(|| foo());
    
    // 先断言确实发生了panic
    assert!(panic_result.is_err());
    
    // 提取panic消息并转换为String类型
    let panic_msg = panic_result.unwrap_err()
        .downcast_ref::<String>()
        .or_else(|| panic_result.unwrap_err().downcast_ref::<&str>().map(|s| s.to_string()))
        .expect("panic消息不是字符串类型");
    
    // 严格断言消息完全一致
    assert_eq!(panic_msg, "foo panic message");
}

方法二:使用Rust 1.64+的kind = "exact"属性

从Rust 1.64版本开始,#[should_panic]支持kind参数,设置为"exact"就能开启完全匹配模式:

#[test]
#[should_panic(expected = "foo panic message", kind = "exact")]
fn foo_test() {
    foo()
}

这种方式更简洁,不需要手动写捕获逻辑,直接通过属性配置就能实现严格匹配。

内容的提问来源于stack exchange,提问作者Rick de Water

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 15:22:40