24.7 Documentation Tests
Rust can compile and execute code examples embedded in documentation comments, ensuring that the examples remain correct over time. These tests are particularly useful for verifying that documentation accurately reflects actual code behavior. For example, in src/lib.rs
:
/// Returns the sum of two integers.
///
/// # Examples
///
/// ```
/// let result = my_crate::add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
When you run cargo test
, Rust detects and tests code blocks in documentation comments. If you do not provide a main()
function in the snippet, Rust automatically wraps the example in an implicit fn main()
and adds an extern crate <cratename>
statement to enable execution. A documentation test passes if it compiles and runs successfully. Using assert!
macros in your examples also helps verify behavior.
24.7.1 Hidden Lines in Documentation Tests
To keep examples simple while ensuring they compile, you can include hidden lines. They start with #
and are omitted in rendered documentation. For example:
/// Returns the sum of two integers.
///
/// # Examples
///
/// ```
/// # use my_crate::add; // Hidden line
/// let result = add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
This hidden use
statement is required for compilation but doesn't appear in the published docs. Running cargo test
confirms that these examples remain valid and up-to-date.
24.7.2 Ignoring Documentation Tests
You can start code blocks with:
```ignore
: The block is ignored by the test harness.```no_run
: The compiler checks the code for errors but does not attempt to run it.
These modifiers are useful for incomplete examples or code that is not meant to run in a test environment.