should_panic
- Rust course
- Intermediate
- Lesson 87/115
- 4 min
Write tests that expect a panic with should_panic.
should_panic
For some functions, panicking on invalid input is the expected behaviour. #[should_panic] counts the test as passed if it panics. With expected, a specific text is also required in the panic message:
fn bol(a: i32, b: i32) -> i32 {
if b == 0 {
panic!("sıfıra bölme");
}
a / b
}
#[test]
#[should_panic(expected = "sıfıra bölme")]
fn sifira_bolme_panik_verir() {
bol(1, 0);
}Without expected, a panic for the wrong reason would also pass the test.
Tests returning Result
For functions returning Result instead of panicking, checking the error case directly is clearer:
fn guvenli_bol(a: i32, b: i32) -> Result<i32, String> {
if b == 0 { return Err("sıfıra bölme".into()); }
Ok(a / b)
}
#[test]
fn sifir_hata_doner() {
assert_eq!(guvenli_bol(1, 0), Err("sıfıra bölme".to_string()));
assert!(guvenli_bol(4, 2).is_ok());
}Practice Panic test
Write the bol function above and a #[cfg(test)] mod tests containing a test marked #[should_panic(expected = "sıfıra bölme")]. In main, print the result of bol(10, 2).
Starter code
fn main() {
// buraya yaz
}Sample solution
fn bol(a: i32, b: i32) -> i32 {
if b == 0 {
panic!("sıfıra bölme");
}
a / b
}
fn main() {
println!("{}", bol(10, 2));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "sıfıra bölme")]
fn sifira_bolme_panik_verir() {
bol(1, 0);
}
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if a <code>#[should_panic]</code> test finishes without panicking?
- It warns
- The test fails Correct answer
- The test passes
- It's skipped
Explanation: If the expected panic didn't happen, the function isn't catching the invalid input.
2 Expected panic
#[test]
#[____(expected = "sıfıra bölme")]
fn sifira_bolme_panik_verir() {
bol(1, 0);
}
#[test]
#[should_panic(expected = "sıfıra bölme")]
fn sifira_bolme_panik_verir() {
bol(1, 0);
}
Explanation: should_panic counts a panicking test as passed.
3 Case and test result
| Term | Meaning |
|---|---|
should_panic + panic |
Passes |
should_panic + no panic |
Fails |
expected doesn't match |
Fails (mismatch) |
Normal test + panic |
Fails (panic) |