Nikita Fedyashev
Nikita Fedyashev

Reputation: 18993

Rust test - how fail verbosely if Result object is not Ok?

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)

Upvotes: 7

Views: 4676

Answers (2)

justinas
justinas

Reputation: 6857

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.

Upvotes: 7

possum
possum

Reputation: 2917

assert! can take multiple arguments, the second of which is a message

https://doc.rust-lang.org/std/macro.assert.html

e.g.

assert!(res.is_ok(), "Whatever you want to say or template");

Upvotes: 3

Related Questions