Add a panic assertion test
This commit is contained in:
parent
90d4dcb5f6
commit
40d69d9539
1 changed files with 30 additions and 4 deletions
|
@ -2,6 +2,20 @@ use rand::Rng;
|
|||
use std::cmp::Ordering;
|
||||
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() {
|
||||
println!("Guess the number!");
|
||||
let secret_number = rand::thread_rng().gen_range(1..=100);
|
||||
|
@ -16,17 +30,17 @@ fn main() {
|
|||
.read_line(&mut guess)
|
||||
.expect("Failed to read line");
|
||||
|
||||
let guess: u32 = match guess.trim().parse() {
|
||||
Ok(num) => num,
|
||||
let guess: Guess = match guess.trim().parse() {
|
||||
Ok(num) => Guess::new(num),
|
||||
Err(_) => {
|
||||
println!("Please type a number!");
|
||||
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::Greater => println!("Too big!"),
|
||||
Ordering::Equal => {
|
||||
|
@ -36,3 +50,15 @@ fn main() {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn greater_than_100() {
|
||||
Guess::new(200);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue