Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you test functions that return Result?

Tags:

testing

rust

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?

like image 731
TorelTwiddler Avatar asked Feb 18 '26 02:02

TorelTwiddler


2 Answers

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(()).

like image 185
FlyingFoX Avatar answered Feb 19 '26 14:02

FlyingFoX


You can simply check if the result is Ok as follows:

assert!(result_function().is_ok())

and when you expect an Err:

assert!(result_function().is_err())

See https://doc.rust-lang.org/std/result/

like image 39
Majid Avatar answered Feb 19 '26 14:02

Majid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!