How to assert io errors in Rust?

TL;DR: Error should implement PartialEq

Result<T, E> only implements PartialEq when T and E also implement PartialEq, but io::Error doesn’t. alex confirm that cause io::Error takes an extra error that implements dyn Error, allowing the user to add extra information lead std to not implement PartialEq.


I see a lot of answer and comment that seem a lot of peoples use io::Error to create their own error. This is NOT a good practice, io::Error should be used only if you deal yourself with io. There is the Error Handling Project Group if you want to learn and share your view about error in Rust.

For now there is some common crate in Rust to make your own error (feel free to add crate):

  • snafu (my favorite)
  • thiserror
  • anyhow
  • quick-error

I don’t totally agree but here a good guide about Error in Rust.


Anyway, the solution that you probably want in your case is just to compare the ErrorKind value. As ErrorKind implements PartialEq this will compile with assert_eq()

use std::io;

fn parse_data(input: i32) -> Result<i32, io::Error> {
    match input {
        0 => Ok(0),
        x => Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("unexpected number {}", x),
        )),
    }
}

#[test]
fn test_parsing_wrong_data() {
    let result = parse_data(1).map_err(|e| e.kind());
    let expected = Err(io::ErrorKind::InvalidData);
    assert_eq!(expected, result);
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)