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
- A test returning
Resultlets you use?inside it. #[should_panic(expected = ...)]matches the message.#[ignore]parks a slow test until asked for.
Keywords and builtins used here
OkResultStringaselsefni32ifletmainmodparses_a_numberrejects_too_many_starsstarssuperu8use
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.
Step 2 of 3 in Tests & docs, step 5 of 12 in Modules, tests & macros.