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?