`should_panic`
#[should_panic] marks a test that is expected to panic. The test fails if the function returns normally. An optional expected substring must appear in the panic message.
Detailed Explanation
Some APIs are defined to panic: slice[i] on a bad index, unwrap on a broken invariant, a constructor that documents "panics if the buffer is empty". You test that with #[should_panic] fn empty_buffer_panics() { Buffer::new(&[]); }. If the function does not panic, the test fails. That is the inverted outcome.
#[should_panic(expected = "empty")] is the form you should prefer. Any panic passes a bare #[should_panic], including a panic from an unrelated unwrap you did not mean to test. The expected string must be a substring of the panic payload. A typo in the message is a failing test after a refactor — that is useful.
Do not use should_panic for errors that should be Result. If the public API returns Err, assert on Err. A should_panic test of a library function that you could have made fallible is a documentation of a weaker API. Inside the crate, testing that an internal debug_assert! fires is more reasonable, and even then a Result is often clearer.
should_panic does not compose with #[test] fn f() -> Result<...>. A Result test that panics is already a failure; adding should_panic is confusing. Keep panic tests as ()-returning functions.
When you write should_panic: a documented panic, with expected. When you write assert!(matches!(r, Err(...))): a fallible API. When you write nothing: do not test that 1 + 1 does not panic.
Prefer testing the public Result even if the current implementation panics internally. A later refactor that returns Err will break should_panic and that break is a gift only if you wanted the panic. If the panic is the API, say so in rustdoc (# Panics) and keep the expected string in sync with that paragraph.
Code Examples
fn first(xs: &[i32]) -> i32 {
xs[0]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "index out of bounds")]
fn empty_slice_panics() {
let _ = first(&[]);
}
}Common Gotchas
Bare `#[should_panic]` accepts any panic
A bug that panics earlier will still pass. Always set `expected`.
Do not hide a `Result` API behind a panic test
If callers should handle the case, return `Err` and assert that.
`expected` is a substring
The full panic includes file and line. Match a stable piece of the message you control.
The attribute sits with `#[test]`
Order is `#[test]` then `#[should_panic]`. Both are required.