The #[test] attribute macro marks a Rust function as an automated test. Function names communicate intent but do not determine discovery; the test framework finds functions carrying the attribute. section 7.1
A test function is Rust’s minimum unit of testing and can validate behavior with assertions or simply fail when an operation returns an error. section 7.1
A small test module commonly combines the attribute with:
- #[cfg(test)] keeps the test module out of production builds. section 7.1
- assert_eq! compares values and panics the test when they differ; assert! validates a Boolean condition. section 7.1
- cargo test compiles, discovers, and runs functions marked with #[test]. section 7.3
A discovered test
In #[cfg(test)] mod tests, #[test] fn it_works() { let result = 2 + 2; assert_eq!(result, 4); } marks it_works for automated execution. Running cargo test reports the test as passed. section 7.1 section 7.3
Listing 7.1 Contents of a newly initialized Rust library
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
let result = 2 + 2;
assert_eq!(result, 4);
}
}
View the complete initialized library test module, including conditional compilation, the test attribute, and an equality assertion. section 7.1
