Featured image of post Introduction to Writing and Running Tests in Rust (cargo test)

Introduction to Writing and Running Tests in Rust (cargo test)

Explains how to write test code in Rust and the procedure for running tests using the cargo test command for beginners. It introduces in detail how to use the #[test] attribute and the output results on success/failure, complete with specific code examples.

Rust runs functions marked with #[test] as tests. This example puts a unit test for an addition function in a #[cfg(test)] module.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
fn add(left: i32, right: i32) -> i32 {
    left + right
}

#[cfg(test)]
mod tests {
    use super::add;

    #[test]
    fn adds_two_numbers() {
        assert_eq!(add(2, 2), 4);
    }
}

cargo test builds and runs the package tests. Passing tests show ok, and the summary includes test result: ok.

1
cargo test

If an assertion fails, that test is marked FAILED and Cargo exits with an error. Paths, line numbers, and timings vary by environment and Rust version.

References

Licensed under CC BY-NC-SA 4.0
Last updated on 2026/11/24 00:00 +0900
comments powered by Disqus