tests3.rs (1288B)
1 struct Rectangle { 2 width: i32, 3 height: i32, 4 } 5 6 impl Rectangle { 7 // Don't change this function. 8 fn new(width: i32, height: i32) -> Self { 9 if width <= 0 || height <= 0 { 10 // Returning a `Result` would be better here. But we want to learn 11 // how to test functions that can panic. 12 panic!("Rectangle width and height must be positive"); 13 } 14 15 Rectangle { width, height } 16 } 17 } 18 19 fn main() { 20 // You can optionally experiment here. 21 } 22 23 #[cfg(test)] 24 mod tests { 25 use super::*; 26 27 #[test] 28 fn correct_width_and_height() { 29 // TODO: This test should check if the rectangle has the size that we 30 // pass to its constructor. 31 let rect = Rectangle::new(10, 20); 32 assert_eq!(rect.width, 10); // Check width 33 assert_eq!(rect.height, 20); // Check height 34 } 35 36 // TODO: This test should check if the program panics when we try to create 37 // a rectangle with negative width. 38 #[test] 39 fn negative_width() { 40 let _rect = Rectangle::new(-10, 10); 41 } 42 43 // TODO: This test should check if the program panics when we try to create 44 // a rectangle with negative height. 45 #[test] 46 fn negative_height() { 47 let _rect = Rectangle::new(10, -10); 48 } 49 }