Panic assertion
The panic assertion checks if a specific piece of code panics:
// Ensure that the code panics
assert_panics!(
|| {
panic!();
}
);
// Ensure that the code panics with a specific message
assert_panics!(
|| {
panic!("hello, world");
},
on_message = |message| {
assert_eq!(message, "hello, world");
}
);
The second call to assert_panics!
takes an on_message
argument. This argument is a closure
that takes a single argument of type String
representing the panic message.
Why not #[should_panic]
?
Rust has a built-in attribute called #[should_panic]
that can be used to check if a unit test will panic:
#[test]
#[should_panic]
fn unit_test() {
panic!();
// Code here will not run
}
There's no reason not to use this, but assert_panics!(...)
provides a bit more granularity and can allow code to continue after the panic:
#[test]
fn unit_test() {
assert_panics!(
|| {
panic!();
}
);
// This code will still run
}