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 which adds two numbers.

pub fn add(a: i32, b: i32) -> i32 {
    a + b

We can write a test for this function in the same file.

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