liveBook · Manning

Test attribute macro

As explained in Refactoring to Rust

The test attribute macro marks a Rust function for discovery and execution as an automated test.

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

How Refactoring to Rust covers it

How deep it goes
Explains function-level discovery and execution, while deferring test-framework internals.
Examples
Uses an it_works function that computes 2 + 2 and checks the result with assert_eq!.
What it assumes
Assumes familiarity with Rust functions and teaches test discovery from the attribute onward.
What you can do after
Apply it via cargo test to define, discover, and run automated Rust tests.
How it connects
Connects test functions with conditional compilation, assertions, unit testing, and cargo test.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.