Macro expecting::expect_err

source ·
macro_rules! expect_err {
    ( $result:expr ) => { ... };
}
Expand description

Expects that the given Result is Err and returns the unwrapped error; otherwise returns early.

§Examples

fn passing_test() -> Result<()> {
    let result: Result<i32> = Err(anyhow!("ruh roh!"));
    let err = expect_err!(result);
    expect!(err.to_string().contains("ruh roh!"));
    Ok(())
}

fn failing_test() -> Result<()> {
    let err = expect_err!(Ok(()));  // returns early
    Ok(())  // won't be reached
}

failing_test() will return early after calling expect_err!. The Err will be wrapped in a descriptive error message such as:

[my/file.rs:12] “expect_err!(result)” Expected Err, got Ok: [ contents ]
[ … wrapped Err details …]