Skip to content

Chapter 11.1 - Explain that it's not possible to expect a test to return an error when the return type is Result #2085

Closed
@TomLouisKeller

Description

@TomLouisKeller

Hy,

In Chapter 11.1 - How to Write Tests - at the bottom of the page it is explained, how to
write a test, when we expect the compiler to panic. The book then goes on to explain how to write a test, when we expect Result::Ok, but when it comes to an expected Result::Err is only states:

You can’t use the #[should_panic] annotation on tests that use Result<T, E>.
Instead, you should return an Err value directly when the test should fail.

I interpret this as we have to write something in the lines of:

#[test]
fn expect_err() -> Result::Err {
    Err(String::from("This is an expected error"))
}

This doesn't work because Result::Err is a variant, not a type.
I've found these two ways to test for Result:Err:

#[test]
fn expect_err() {
    let res: Result<(), &str> = Err("This is an expected error");

    res.expect_err("This should have panicked");
    // or
    assert_eq!(res.is_ok(), false);
}

It would be nice if there was a code example, after the quoted sentence.

Thank you very much to everyone who worked on the book. I thoroughly enjoy it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions