24.5 Tests That Should Panic
24.5.1 #[should_panic]
You can mark a test that is expected to panic:
#[test]
#[should_panic]
fn test_for_panic() {
panic!("This function always panics");
}
This test passes if the function panics.
24.5.2 The expected
Parameter
You can also ensure that a panic message contains a specific substring:
#[test]
#[should_panic(expected = "division by zero")]
fn test_divide_by_zero() {
let _ = 1 / 0; // "attempt to divide by zero"
}
If the panic message does not match "division by zero"
, the test fails. This helps verify that your code panics for the correct reason.