知识卡片
分辨预期的 panic
#[should_panic] 标在测试函数上,函数发生 panic 时用例通过。若同一路径可能从多个位置 panic,可写 #[should_panic(expected = "…")],用有区分度的消息子串锁定预期失败。比如输入 200,应触发 Guess 的上限消息。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 编写自动化测试 Checking for Panics with should_panic · 查看原书依据
Tests that use should_panic can be imprecise. A should_panic test would pass even if the test panics for a different reason from the one we were expecting. To make should_panic tests more precise, we can add an optional expected parameter to the should_panic attribute. The test harness will make sure that the failure message contains the provided text.
参考来源
- 位置:《The Rust Programming Language(第2版)》第11章 编写自动化测试(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c11.xhtml`,块 0118)
- 结论依据:原文指出任意 panic 会造成误通过,并展示了按消息子串约束失败原因。
- 原始内容:Tests that use should_panic can be imprecise. A should_panic test would pass even if the test panics for a different reason from the one we were expecting. To make should_panic tests more precise, we can add an optional expected parameter to the should_panic attribute. The test harness will make sure that the failure message contains the provided text.