Unit test function that is supposed to panic!?


Short Version: How do I unit test a function that is supposed to panic ?

Long Version: I have a “sanity check” function which checks that certain structures are consistent – and on error, it the function is supposed to panic!(). Is there a way to unit test something of the form:

  1. here is a bad inconsistent state
  2. we want to make sure this function panic!()'s on iti

fn test_foo() {


@sfackler :

LOL. Was unaware of #[should_panic]. Issue resolved. Thanks!


As I recall, should_panic used to only work in doctests; has that been fixed?


It’s always worked in unit tests AFAIR.


My mistake, I was thinking of compile_fail.


If you wanted to be more fine-grained (eg. make sure the right part of the code panics, not the setup, or that the panic message contains certain words), you can also use catch_unwind, extract the error and handle that.


@vorner You can use #[should_panic(expected = "message")] for that. This will succeed only for panic!("message").