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);
}
}
The
my_module
module contains a simple functionadd_two_numbers
that takes two integers and returns their sum.The
#[cfg(test)]
attribute ensures that the following module (tests
) is compiled only when running tests.The
tests
module is created to contain unit tests.The
use super::my_module;
statement brings themy_module
module into scope for the tests.The first test case (
test_add_two_numbers_positive
) is defined with the#[test]
attribute. It tests theadd_two_numbers
function with positive integers.Inside the test case:
let num1 = 2;
andlet num2 = 3;
are used to set up the input values.let result = my_module::add_two_numbers(num1, num2);
calls the function being tested.assert_eq!(result, 5);
checks that the result matches the expected value.The second test case (
test_add_two_numbers_negative
) is similar but tests the function with one negative integer.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.