Testing & Documentation

Testing and documentation are part of the language and toolchain, not add-ons. #[test] unit tests, tests/ integration tests, and /// doc-tests all run with one command: cargo test.

Unit Tests

Unit tests live in a #[cfg(test)] module inside the same file as the code they test, which means they are stripped from release binaries and can inspect private helper functions directly. Annotate each test function with #[test]; Cargo compiles and runs them in parallel by default.

pub fn add(left: usize, right: usize) -> usize {
    left + right
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_adds() {
        assert_eq!(add(2, 2), 4);
    }

    #[test]
    fn it_adds_zero() {
        assert_eq!(add(0, 7), 7);
    }
}

Run the test suite from the project root with cargo test. Because tests run concurrently, avoid sharing mutable global state or hard-coded temporary file paths across test functions.

cargo test        # compiles and runs every #[test]

Assertions

Rust ships a family of assertion macros. assert! checks a boolean condition, assert_eq! and assert_ne! compare two values and print both sides on failure using Debug formatting, and #[should_panic] verifies that invalid inputs fail loudly as intended.

#[cfg(test)]
mod tests {
    #[test]
    fn comparisons() {
        assert_eq!(4, 4);           // equal
        assert_ne!(4, 5);           // not equal
        assert!(2 + 2 == 4);        // boolean condition
    }

    #[test]
    #[should_panic(expected = "attempt to divide by zero")]
    fn divides_by_zero() {
        let _n = 1i32 / 0;          // panics as expected
    }
}

Integration Tests

Integration tests exercise your crate as an external consumer would, from separate files under the top-level tests/ directory. Unlike unit tests, each file in tests/ is compiled as its own crate and can only call your library's pub API.

hello/
├── src/lib.rs
└── tests/
    └── integration.rs

Import your crate by its package name from Cargo.toml and verify end-to-end behavior across modules:

// tests/integration.rs — imports the library crate `hello`
use hello::add;

#[test]
fn test_through_public_api() {
    assert_eq!(add(10, 32), 42);
}

Doc-tests

Code blocks inside /// documentation comments are compiled and executed by cargo test as standalone examples. This catches stale documentation automatically whenever a function signature or return value changes.

/// Adds two unsigned integers.
///
/// # Examples
///
/// ```
/// let result = my_crate::add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(left: usize, right: usize) -> usize {
    left + right
}

You can run only documentation tests during quick edits or generate the full HTML reference locally with Cargo:

cargo test --doc    # run only the doc-tests
cargo doc --open    # build the rendered docs
Practice move: add a deliberately wrong assert_eq! to the lab examples, run cargo test, and read the diff the assertion prints.