Rust has built-in support for testing with the cargo and assert. We can write tests in Rust using the #[test] attribute and the assert! macro. The cargo command-line interface can be used to run the tests. The tests can be written in the same file as the code being tested, or in a separate file.
Writing Tests
Suppose we have a function add in main.rs which adds two numbers.
// main.rs
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
We can write a test for this function in the same file.
// main.rs
#[test]
fn test_add() {
let result = add(2, 3);
assert_eq!(5, result);
}
Running Tests
To run the tests, use the cargo test command.
cargo test