Skip to content

Commit 7898fcf

Browse files
added a shorthand for the #[should_panic(expected = "msg")
#[should_panic = "msg"] is shorthand for #[should_panic(expected = "msg")]
1 parent c9d151f commit 7898fcf

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/testing/unit_testing.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,10 @@ To check functions that should panic under certain circumstances, use attribute
107107
the text of the panic message. If your function can panic in multiple ways, it helps
108108
make sure your test is testing the correct panic.
109109

110+
**Note**: Rust also allows a shorthand form `#[should_panic = "message"]`, which works
111+
exactly like `#[should_panic(expected = "message")]`. Both are valid; the latter is more commonly
112+
used and is considered more explicit.
113+
110114
```rust,ignore
111115
pub fn divide_non_zero_result(a: u32, b: u32) -> u32 {
112116
if b == 0 {
@@ -137,6 +141,12 @@ mod tests {
137141
fn test_specific_panic() {
138142
divide_non_zero_result(1, 10);
139143
}
144+
145+
#[test]
146+
#[should_panic = "Divide result is zero"] // This also works
147+
fn test_specific_panic_shorthand() {
148+
divide_non_zero_result(1, 10);
149+
}
140150
}
141151
```
142152

@@ -149,8 +159,9 @@ running 3 tests
149159
test tests::test_any_panic ... ok
150160
test tests::test_divide ... ok
151161
test tests::test_specific_panic ... ok
162+
test tests::test_specific_panic_shorthand ... ok
152163

153-
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
164+
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
154165

155166
Doc-tests tmp-test-should-panic
156167

0 commit comments

Comments
 (0)