In this lesson, you will learn how to trigger Rust’s built-in test runner and organize your code to allow Cargo to automatically discover your tests.
The #[test] Attribute
Rust includes a first-class testing framework built right into the compiler. To define a unit test, you simply add the #[test] attribute above any function. When you run your test suite, Cargo scans your project, finds every function marked with this attribute, and executes them in isolation to verify they behave as expected.
For example, in your src/lib.rs or src/main.rs, you might write:
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[test]
fn test_addition() {
assert_eq!(add(2, 2), 4);
}
Executing the Test Suite
Because testing is part of the cargo toolchain, you don’t need to install external test runners. Simply open your terminal in your project root and run:
cargo test
When you execute this command, Cargo performs three main tasks:
- Compilation: It compiles your project in "test mode," which enables the test-specific code blocks.
- Discovery: It traverses your crate structure to find every function decorated with
#[test]. - Execution: It runs each test in a separate thread. If a function completes without panicking, the test passes; if the code triggers an
assert!failure or panics, the test fails.
Managing Test Discovery
By default, Cargo looks for tests everywhere in your project. A common professional pattern is to place tests inside a cfg(test) module at the bottom of your file. This ensures that your testing code is only compiled when you explicitly run cargo test, keeping your production binary lean:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn internal_logic_check() {
assert!(true);
}
}
By wrapping tests in this module, you keep your source code organized, and Cargo’s discovery mechanism will still automatically find and run every test inside that module whenever you invoke the command-line interface.
Key Takeaway: Use the #[test] attribute to mark functions and trigger them with cargo test to let the Rust toolchain automatically discover and verify your code.