Idiomatic way of testing Result<T, Error>?

I am trying to write test cases for functions which return Result<T, Error>.
How can I write tests for checking T is returned or checking Error is returned?

4 Likes

Can't you just try this?

fn check<T>(res: Result<T, Error>) {
    match res {
        Ok(val) => { println!("got the T") }
        Err(e) => { println!("got the Err") }
    }

}

Yes, now I'm writing like the code below.

match fs::metadata(path) {
    Ok(_) => assert!(false, "db file should not exist"),
    Err(_) => assert!(true),
}

Is there a better way?

1 Like

assert!(fs::metadata(path).is_err(), "db file should not exist")

12 Likes

I like this.
Thanks!

2 Likes

Found a better way which includes testing for specific errors

https://stackoverflow.com/questions/53124930/how-do-you-test-for-a-specific-rust-error/53124931#53124931

2 Likes