typestar

Testing errors and panics in Rust

Tests can return Result, and should_panic asserts the failure you expect.

fn stars(value: i32) -> Result<u8, String> {
    if (0..=3).contains(&value) {
        Ok(value as u8)
    } else {
        panic!("stars out of range: {value}");
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_a_number() -> Result<(), std::num::ParseIntError> {
        let n: i32 = "3".parse()?;
        assert_eq!(stars(n).unwrap(), 3);
        Ok(())
    }

    #[test]
    #[should_panic(expected = "out of range")]
    fn rejects_too_many_stars() {
        stars(9).unwrap();
    }
}

fn main() {
    println!("{:?}", stars(2));
}

How it works

  1. A test returning Result lets you use ? inside it.
  2. #[should_panic(expected = ...)] matches the message.
  3. #[ignore] parks a slow test until asked for.

Keywords and builtins used here

The run, in numbers

Lines
29
Characters to type
471
Tokens
156
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 89 seconds.

Type this snippet

Step 2 of 3 in Tests & docs, step 5 of 12 in Modules, tests & macros.

← Previous Next →