My use case is pretty simple - if an actual object is not an Ok variant, I would like this test to fail explicitly by showing what it contains instead:
fn test_foo() {
let actual = fn_that_returns_result();
// not verbose enough in case it is actually an Err:
// assert!(res.is_ok());
}
I can not make an exact comparison here because Ok variant's inner state is dynamic.
The method below kind of works but I'm wondering if it's fine or perhaps there's a more idiomatic solution to this?
fn test_foo() {
let actual = fn_that_returns_result();
match res {
Ok(_) => {},
Err(err) => panic!("{}", err) // anyhow::Error
}
}
Update: just to be clear, I would like the original error to stay intact and not be overwritten in assert(therefore cant use .expect
or override it via assert!
's 2nd argument)
In Rust, tests are considered failed when they panic. In fact, that's about all that macros like assert!
do under the hood: evaluate a condition, and if it is not met, panic with an error message.
Result
includes methods like unwrap and expect, both of which panic with the error value as the message if the Err
variant is held, and as such will fail your test.