Add a panic assertion test

This commit is contained in:
Manuel Thalmann 2025-03-02 23:50:58 +01:00
parent 90d4dcb5f6
commit 40d69d9539

View file

@ -2,6 +2,20 @@ use rand::Rng;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::io; use std::io;
pub struct Guess {
value: i32,
}
impl Guess {
pub fn new(value: i32) -> Guess {
if value < 1 || value > 100 {
panic!("Guess value must be between 1 and 100, got {value}.");
}
Guess { value }
}
}
fn main() { fn main() {
println!("Guess the number!"); println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100); let secret_number = rand::thread_rng().gen_range(1..=100);
@ -16,17 +30,17 @@ fn main() {
.read_line(&mut guess) .read_line(&mut guess)
.expect("Failed to read line"); .expect("Failed to read line");
let guess: u32 = match guess.trim().parse() { let guess: Guess = match guess.trim().parse() {
Ok(num) => num, Ok(num) => Guess::new(num),
Err(_) => { Err(_) => {
println!("Please type a number!"); println!("Please type a number!");
continue; continue;
}, },
}; };
println!("You guessed: {guess}"); println!("You guessed: {}", guess.value);
match guess.cmp(&secret_number) { match guess.value.cmp(&secret_number) {
Ordering::Less => println!("Too small!"), Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"), Ordering::Greater => println!("Too big!"),
Ordering::Equal => { Ordering::Equal => {
@ -36,3 +50,15 @@ fn main() {
} }
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn greater_than_100() {
Guess::new(200);
}
}