Why are error messages not printing during tests with thiserror?

I am using the thiserror crate to implement a custom error type. From the crate's documentation:

A Display impl is generated for your error if you provide #[error("...")] messages on the struct or each variant of your enum

I've written some tests to test the error is working, and am just calling unwrap() in the tests. However, the error message that is printing is not the custom error message I've defined, it is just panicked at 'called Result::unwrap()on anErr value, followed by the enum variant.

How do I test the error message is printing properly? Why is it not printing in the first place? Is it because of unwrap?

If you want to test the derived Display impl for your error you should do :

let error = Error { ... };
assert_eq!("my error", error.to_string());

But this is pretty silly since this isn't guaranteed to be stable. (the Display trait is not made for stable output)

Result::unwrap uses Debug implementation of the error, not Display.

I think you have Debug and Display backwards. Debug is the one that doesn't promise stable results (for standard types or derived implementations). Any explicit implementation of Display is just as stable as its author wants (and so is an explicit implementation of Debug).

Yes, what I meant was it probably shouldn't be relied upon, thank you

Well I want to test if the error message is printing correctly, so I should use Display, instead of unwrap which will print the Debug output. But I am confused on your code to achieve that. Currently, I am expecting an error, so I just call unwrap, but this just does the debug output. Is there a way where I can trigger the error I am expecting at get the Display output? Thank you.

thiserror derives a Display impl, that gives a ToString impl thanks to which you can call to_string on your error type.

struct Error {

fn foo() {
    // build an error
    let error = Error { ... };
    assert_eq!("the expected error", error.to_string());

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.