When I'm writing code, I often want to be able to test that it returns a the right error in a particular situation. With hand-implemented errors, I would use a match statement for this, since errors can't be expected to implement PartialEq. Normally I would make this more informative and concise by using assert_matches from the matches crate. For example:
use std::error::Error;use std::fmt;use std::fmt::{Display,Formatter};#[derive(Debug)]pubenumMyError{BadThingHappened{badness_level:usize,},}implDisplayforMyError{fnfmt(&self,formatter:&mutFormatter) -> fmt::Result{unimplemented!()// I have omitted this}}implErrorforMyError{}fnmy_fn() -> Result<(),MyError>{Err(MyError::BadThingHappened{badness_level:9})}fnmain(){matchmy_fn(){Err(MyError::BadThingHappened{badness_level:9}) => (),
_ => panic!("the wrong error was returned")}}
How could I test this behavior with a failure error? For example:
#[macro_use]externcrate failure;use failure::Error;#[derive(Debug,Fail)]pubenumMyError{#[fail(display = "a bad thing of level {} happened", badness_level)]BadThingHappened{badness_level:usize,},}fnmy_fn() -> Result<(),Error>{Err(Error::from(MyError::BadThingHappened{badness_level:9}))}fnmain(){// What would I put here to test that my_fn has returned the correct error?}
The text was updated successfully, but these errors were encountered:
Would using downcast_ref be a good way to do this? It appears to work for the use case above.
fnmain(){matchmy_fn().expect_err("my_fn should return an error").downcast_ref().expect("the wrong type of error was returned"){MyError::BadThingHappened{badness_level:9} => (),
_ => panic!("the wrong error was returned"),}}
Sign up for freeto subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Labels
None yet
1 participant
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.
When I'm writing code, I often want to be able to test that it returns a the right error in a particular situation. With hand-implemented errors, I would use a
match
statement for this, since errors can't be expected to implementPartialEq
. Normally I would make this more informative and concise by using assert_matches from the matches crate. For example:How could I test this behavior with a
failure
error? For example:The text was updated successfully, but these errors were encountered: