Skip to content

added a shorthand for the #[should_panic(expected = "msg") #1931

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/testing/unit_testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,10 @@ To check functions that should panic under certain circumstances, use attribute
the text of the panic message. If your function can panic in multiple ways, it helps
make sure your test is testing the correct panic.

**Note**: Rust also allows a shorthand form `#[should_panic = "message"]`, which works
exactly like `#[should_panic(expected = "message")]`. Both are valid; the latter is more commonly
used and is considered more explicit.

```rust,ignore
pub fn divide_non_zero_result(a: u32, b: u32) -> u32 {
if b == 0 {
Expand Down Expand Up @@ -137,6 +141,12 @@ mod tests {
fn test_specific_panic() {
divide_non_zero_result(1, 10);
}

#[test]
#[should_panic = "Divide result is zero"] // This also works
fn test_specific_panic_shorthand() {
divide_non_zero_result(1, 10);
}
}
```

Expand All @@ -149,8 +159,9 @@ running 3 tests
test tests::test_any_panic ... ok
test tests::test_divide ... ok
test tests::test_specific_panic ... ok
test tests::test_specific_panic_shorthand ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Doc-tests tmp-test-should-panic

Expand Down