liveBook · Manning

Doc test

As explained in Refactoring to Rust

A documentation test is an automated test generated by compiling and running executable code examples embedded in documentation.

A doc test is an executable example embedded in a documentation comment. Rust extracts each Markdown code block, compiles it as a separate crate, and runs it through the normal test system. This keeps public-API examples from becoming outdated. section 7.1 section 7.1.1

Testing a documented function

Document a public function with an example such as `assert_eq!(testing::add(2, 2), 4);` inside a Markdown code block. Run `cargo test` to execute both ordinary tests and doc tests. A wrong assertion fails at runtime; passing a string where an `i32` is required fails during compilation. Correct examples pass alongside the crate's other tests. section 7.1.1

Listing 7.6 Documentation tests
/// Add together two i32 numbers and return the result of that addition
/// ```
/// assert_eq!(testing::add(2, 2), 4);
/// ```
///
/// ```
/// use testing::add;
/// assert_eq!(add(2, 2), 5);
/// ```
///
/// ```
/// use testing::add;
/// assert_eq!(add("hello", 2), 5);
/// ```
pub fn add(x: i32, y: i32) -> i32 {
  x + y
}

Inspect a complete documentation comment containing one passing assertion, one failing assertion, and one non-compiling example. section 7.1.1

How Refactoring to Rust covers it

How deep it goes
Explains Markdown extraction, separate-crate compilation, failure reporting, and implicit-main line-number limitations.
Examples
Uses an `add` function with passing, assertion-failing, and type-error examples.
What it assumes
Assumes a Rust crate with a public function and teaches documentation comments and executable examples incrementally.
What you can do after
Operate Cargo to validate documentation examples and interpret runtime or compilation failures.
How it connects
Connects documentation comments, Markdown, public APIs, compilation errors, unit tests, and Cargo.

Also explained in

Compare how 2 books explain doc 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.