Doc Tests
In this page:
Writing a Doc Test
A fenced code block inside a /// documentation comment above a function is automatically treated as a runnable example and executed by cargo test.
Example: Writing a Doc Test
/// Adds one to the given number.
///
/// ```
/// let result = my_project::add_one(5);
/// assert_eq!(result, 6);
/// ```
pub fn add_one(n: i32) -> i32 {
n + 1
}
fn main() {
println!("add_one(5) = {}", add_one(5));
}
Login to try C/C++/Java/PHP code in the editor
Doc Tests Keep Examples Honest
Because the example in the doc comment is actually compiled and executed, if the function's behavior ever changes in a way that breaks the example, cargo test will fail and alert you.
Example: Doc Tests Keep Examples Honest
/// Doubles the given number.
///
/// ```
/// assert_eq!(my_project::double(3), 6);
/// ```
pub fn double(n: i32) -> i32 {
n * 2
}
fn main() {
println!("double(3) = {}", double(3));
}
Login to try C/C++/Java/PHP code in the editor
Multiple Assertions in One Doc Test
A single doc test's code block can contain several statements and multiple assertions, just like an ordinary test function, to cover a few related cases at once.
Example: Multiple Assertions in One Doc Test
/// Checks whether a number is positive.
///
/// ```
/// assert!(my_project::is_positive(5));
/// assert!(!my_project::is_positive(-3));
/// ```
pub fn is_positive(n: i32) -> bool {
n > 0
}
fn main() {
println!("is_positive(5) = {}", is_positive(5));
println!("is_positive(-3) = {}", is_positive(-3));
}
Login to try C/C++/Java/PHP code in the editor
Running Doc Tests
cargo test automatically discovers and runs every doc test alongside unit and integration tests, giving one unified command for verifying all three kinds of tests.
Example: Running Doc Tests
cargo test
⚠️ Run this command in your terminal.
- Writing an example in a doc comment without wrapping it in triple backticks, so
cargo testnever recognizes it as a doc test. - Letting a doc example go stale after changing the function's behavior, when
cargo testwould have caught the mismatch automatically. - Forgetting doc tests need to actually compile and run successfully, including any
assert_eq!checks placed inside them.
- A code block inside a
///doc comment, fenced with triple backticks, is automatically compiled and run as a test. - Doc tests keep documentation examples accurate, since a broken example fails
cargo testjust like a normal test. assert_eq!and similar macros can be used directly inside a doc test's code block to verify behavior.- Doc tests run as part of
cargo test, alongside unit and integration tests.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: