From 8f14544c14efc7e591ef1dd73ac028a2c2e5e2d6 Mon Sep 17 00:00:00 2001 From: Jordan Gong Date: Fri, 4 Sep 2020 20:46:24 +0800 Subject: Write tests --- tests/src/lib.rs | 126 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 tests/src/lib.rs (limited to 'tests/src/lib.rs') diff --git a/tests/src/lib.rs b/tests/src/lib.rs new file mode 100644 index 0000000..8742a00 --- /dev/null +++ b/tests/src/lib.rs @@ -0,0 +1,126 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +impl Rectangle { + fn can_hold(&self, other: &Rectangle) -> bool { + self.width > other.width && self.height > other.height + } +} + +pub fn add_two(a: i32) -> i32 { + a + 2 +} + +pub fn greeting(name: &str) -> String { + format!("Hello {}!", name) + // format!("Hello!") +} + +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); + // } + if value < 1 { + panic!( + "Guess value must be greater than or equal to 1, got {}.", + value + ); + } else if value > 100 { + panic!( + "Guess value must be less than or equal to 100, got {}.", + value + ); + } + + Guess { value } + } +} + +#[cfg(test)] +mod tests { + // #[test] + // fn exploration() { + // assert_eq!(2 + 2, 4); + // } + + // #[test] + // fn another() { + // panic!("Make this test fail"); + // } + + use super::*; + + #[test] + fn lager_can_hold_smaller() { + let larger = Rectangle { + width: 8, + height: 7, + }; + + let smaller = Rectangle { + width: 5, + height: 1, + }; + + assert!(larger.can_hold(&smaller)); + } + + #[test] + fn smaller_can_hold_larger() { + let larger = Rectangle { + width: 8, + height: 7, + }; + + let smaller = Rectangle { + width: 5, + height: 1, + }; + + assert!(!smaller.can_hold(&larger)); + } + + #[test] + fn it_adds_two() { + assert_eq!(4, add_two(2)); + } + + #[test] + fn greeting_contains_name() { + let result = greeting("Jordan"); + assert!( + result.contains("Jordan"), + "Greeting did not contain name, value was `{}`", + result + ); + } + + // #[test] + // #[should_panic] + // fn greater_than_100() { + // Guess::new(200); + // } + + #[test] + #[should_panic(expected = "Guess value must be less than or equal to 100")] + fn greater_than_100() { + Guess::new(200); + } + + #[test] + fn it_works() -> Result<(), String> { + if 2 + 2 == 4 { + Ok(()) + } else { + Err(String::from("two plus two does not equal to four")) + } + } +} -- cgit v1.2.3