简体   繁体   中英

Rust panic unit test - specifics of matching the error message

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM