testingrust

How do you test functions that return Result?


I have a function that returns Result<(), MyError> where:

enum MyError {Error1, Error2}

I am currently doing the following:

#[test]
fn test_result_function() {
    assert_eq!((), result_function().unwrap());
}

This works but seems awkward. At first I was going to do:

assert!(result_function().is_ok());

but when it wasn't ok, the test result didn't give the error anywhere. How should I go about testing this function?


Solution

  • How about

    assert_eq!(Ok(()), result_function());
    

    this needs

    #[derive(PartialEq,Debug)]
    enum MyError{Error1, Error2}
    

    to work and will tell you

    `(left == right)` (left: `Ok(())`, right: `Err(Error1)`)'
    

    when testing when your result_function returns an Error1 when the test says it should return Ok(()).