From e7f8215de95ad362c5e3d3179220f4c66e5929a0 Mon Sep 17 00:00:00 2001 From: laurens Date: Sun, 13 Sep 2020 14:18:28 +0200 Subject: [PATCH] Add example of unit tests in rectangles --- rectangles/src/main.rs | 97 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/rectangles/src/main.rs b/rectangles/src/main.rs index e1265e4..ba131a0 100644 --- a/rectangles/src/main.rs +++ b/rectangles/src/main.rs @@ -20,6 +20,23 @@ impl Rectangle { fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } + + // convenience function to show use of Result in tests + fn return_result(&self, is_succes: bool) -> Result<(), ()> { + if is_succes { + Ok(()) + } else { + Err(()) + } + } + + // convenience function to show panic used in tests + fn return_panic(&self, is_panic: bool) { + if is_panic { + panic!("HEEELP"); + } + } + } fn main() { @@ -79,3 +96,83 @@ fn area_tuple(dimensions: (u32, u32)) -> u32 { fn area_struct(rect: &Rectangle) -> u32 { rect.width * rect.height } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn square() { + let sq = Rectangle::square(4); + + assert_eq!(sq.width, sq.height); + } + + #[test] + fn area() { + let width = 4; + let height = 5; + let rect = Rectangle::build_rectangle(width, height); + + assert_eq!(rect.area(), width * height); + } + + #[test] + fn larger_can_hold_smaller() { + let smaller = Rectangle::build_rectangle(3, 4); + let larger = Rectangle::build_rectangle(5, 6); + + assert!(larger.can_hold(&smaller)); + } + + #[test] + fn smaller_cannot_hold_larger() { + let smaller = Rectangle::build_rectangle(3, 4); + let larger = Rectangle::build_rectangle(5, 6); + + assert!(!smaller.can_hold(&larger)); + } + + #[test] + fn result_success() -> Result<(), ()> { + let rect = Rectangle::build_rectangle(3, 4); + + rect.return_result(true)?; + + Ok(()) + } + + #[test] + fn result_will_fail_with_result() -> Result<(), ()> { + let rect = Rectangle::build_rectangle(3, 4); + + rect.return_result(false)?; + + Ok(()) + } + + #[test] + #[should_panic(expected = "HEEELP")] + fn result_panic() { + let rect = Rectangle::build_rectangle(3, 4); + + rect.return_panic(true); + } + + #[test] + #[should_panic] + fn result_will_not_panic_and_fail() { + let rect = Rectangle::build_rectangle(3, 4); + + rect.return_panic(false); + } + + #[test] + #[should_panic(expected = "HEEEEEEEEEEEEEEEEEEEELP")] + fn result_will_panic_but_with_wrong_message_and_fail() { + let rect = Rectangle::build_rectangle(3, 4); + + rect.return_panic(false); + } + +}