What's the Rust way to unit test for an error?


#1

In chapter 12 of The Rust Book, I’m writing unit tests for the Config::new(args: &[String]) -> Result<Config, &'static str> function. I come from a Java and JUnit background and would assert that an exception is thrown. I’m using a match expression to test that an Error variant of the Result enum is returned:

#[test]
fn no_arguments_creating_config_is_error() {
    let args = vec!(String::from("binary"));
    match Config::new(&args) {
        Err(e) => assert_eq!(e, "not enough arguments"),
        Ok(_) => panic!("test should not reach here"),
    }
}

I don’t like that I need to include an arm for the Ok variant. A slightly better alternative would be to use an if let:

if let Err(e) = Config::new(&args) {
    assert_eq!(e, "not enough arguments")
}

I’m wondering if there is a better way to unit test the Error condition?


#2
assert_eq!(Config::new(&args), Err("not enough arguments"))

#3

Hadn’t considered that, thanks.

#[derive(Debug, PartialEq)]

Need to derive Debug and PartialEq on the Config struct too.


#4

You could also do

assert_eq!(Config::new(&args).err(), Some("not enough arguments"))

#5

In case you want to check if something should panic, then you can use the #[should_panic] attribute on the test function.

#[test]
#[should_panic]
fn panics() {
    panic!();
}