Tests

  • To change a function into a test function, add #[test] on the line before fn.

  • You can run the test using command cargo test.

  • By convention, test functions reside in a module named tests, which is usually placed at the bottom of the file containing the code to be tested.

  • We can check panics adding #[should_panic] attributes.

tests1.rs

// Tests are important to ensure that your code does what you think it should
// do.

fn is_even(n: i64) -> bool {
    n % 2 == 0
}

fn main() {
    // You can optionally experiment here.
}

#[cfg(test)]
mod tests {
    // Import `is_even`. You can use a wildcard to import everything in
    // the outer module.
    use super::is_even;

    #[test]
    fn you_can_assert() {
        // Test the function `is_even` with some values.
        assert!(is_even(10));
        assert!(!is_even(5));
    }
}
  • In this exercise we need to test the functions is_even using assert!.

  • Assert macro accept bool type, will success if value true and fails/panics when value is false.

  • So we need to add two cases for even and odd input like this.

test2.rs

  • Similar like previous exercise we need to add test cases for function power_of_2.

  • But this time using assert_eq.

    • It will assert if given two values are equal.

    • If not it will fail/panic.

  • So let's add the test cases like this:

tests3.rs

  • First task in this exercise is to fix assert_eq! in test function correct_width_and_height().

  • We just need to put correct fields like this:

  • Second have test functions negative_width and negative_height that check if we give negative value when calling Rectangle::new it should panic.

  • We can check panics adding #[should_panic] attributes.

Last updated