rust unit test display

// main.rs

// Module to be tested
mod my_module {
    pub fn add_two_numbers(a: i32, b: i32) -> i32 {
        a + b
    }
}

// Unit tests
#[cfg(test)]
mod tests {
    use super::my_module;

    // Test case 1
    #[test]
    fn test_add_two_numbers_positive() {
        // Arrange
        let num1 = 2;
        let num2 = 3;

        // Act
        let result = my_module::add_two_numbers(num1, num2);

        // Assert
        assert_eq!(result, 5);
    }

    // Test case 2
    #[test]
    fn test_add_two_numbers_negative() {
        // Arrange
        let num1 = -2;
        let num2 = 3;

        // Act
        let result = my_module::add_two_numbers(num1, num2);

        // Assert
        assert_eq!(result, 1);
    }
}
  1. The my_module module contains a simple function add_two_numbers that takes two integers and returns their sum.

  2. The #[cfg(test)] attribute ensures that the following module (tests) is compiled only when running tests.

  3. The tests module is created to contain unit tests.

  4. The use super::my_module; statement brings the my_module module into scope for the tests.

  5. The first test case (test_add_two_numbers_positive) is defined with the #[test] attribute. It tests the add_two_numbers function with positive integers.

  6. Inside the test case:

  7. let num1 = 2; and let num2 = 3; are used to set up the input values.
  8. let result = my_module::add_two_numbers(num1, num2); calls the function being tested.
  9. assert_eq!(result, 5); checks that the result matches the expected value.

  10. The second test case (test_add_two_numbers_negative) is similar but tests the function with one negative integer.

  11. The entire file serves as an example of how unit tests can be structured in Rust. The cargo test command can be used to run the tests in the project.