Rust panic unit test - specifics of matching the error message

Viewed 1154

I'm looking for a way to assert that a piece of code panics, and that the panic message contains a particular string. I came up with the following which appears to work:

let actual = std::panic::catch_unwind(|| decode(notation.to_string()));
assert!(actual.is_err());
let err = *(actual.unwrap_err().downcast::<String>().unwrap());
assert!(err.contains("Invalid"));

I know that I can use #[should_panic] and that it lets me specify a message to check for, but I only want to partially match the exact error message.

1 Answers

Use #[should_panic(expected = "substring of panic message")]

Example

fn some_panic_function() {
    panic!("abc substring of panic message abc");
}

#[test]
#[should_panic(expected = "substring of panic message")]
fn test_some_panic_function() {
    some_panic_function();
}

From this https://doc.rust-lang.org/book/ch11-01-writing-tests.html

Related