Unit test function that is supposed to panic!?


#1

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

#2
#[test]
#[should_panic]
fn test_foo() {
    panic!("blammo");
}

#3

@sfackler :

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


#4

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


#5

It’s always worked in unit tests AFAIR.


#6

My mistake, I was thinking of compile_fail.


#7

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.


#8

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