How to Write Doc Tests That Also Serve as Examples

Write doc tests using /// comments with executable examples and run mdbook test to verify they work.

Write doc tests by adding /// comments above your function containing executable code, then run mdbook test to verify them. This approach uses the rustdoc tool to compile and execute the examples as tests, ensuring your documentation stays accurate.

/// Adds two numbers.
///
/// # Examples
///
/// ```
/// let result = add(2, 3);
/// assert_eq!(result, 5);
/// ```
fn add(a: i32, b: i32) -> i32 {
    a + b
}

Run the tests with:

mdbook test