Skip to content
RustLearn

Module 16 — Testing, Docs & Tooling

Goal

Unit, integration and documentation tests, plus clippy, rustfmt, benchmarks and a CI pipeline that keeps a crate honest.

Start here — what this module is really about

Rust ships testing in the language and the build tool, so there is nothing to choose, install or configure. Write a function, mark it #[test], run cargo test. That low friction is the point: the tests live next to the code and there is no reason not to write them.

There are three kinds, and the distinction is about what you are testing through:

  • Unit tests live in the same file as the code, inside a mod tests block. They can reach private functions, because they are inside the module. Use them for the small logical pieces.
  • Integration tests live in a separate tests/ folder and are compiled as separate crates. They can only see your public API — which is exactly the point: they test your library the way a user experiences it.
  • Documentation tests are the code examples in your /// comments. cargo test compiles and runs them, so an example that goes stale breaks the build.

That third one is genuinely unusual and worth adopting immediately. Every other language's README examples rot silently; Rust's cannot.

The second half of the module is the tooling that keeps a crate honest: rustfmt (ends formatting arguments by deciding for everyone), clippy (a linter that has read the whole standard library and will tell you your six lines are one method call), and a CI configuration that runs all of it on every push.

The one sentence to remember: unit tests check the pieces from inside, integration tests check the public API from outside, and doc tests make sure your documentation is not lying.

Learning objectives

  • Write unit, integration, and documentation tests
  • Use the assertion macros and test attributes fluently
  • Organize test modules and test private functions
  • Use clippy, rustfmt, and useful cargo subcommands
  • Set up benchmarking and basic CI

16.1 Unit tests

Unit tests live in the same file as the code, in a module marked #[cfg(test)] so they're compiled only for cargo test:

rust
pub fn add(a: i32, b: i32) -> i32 { a + b }

fn internal_helper(x: i32) -> i32 { x * 2 }   // private

#[cfg(test)]
mod tests {
    use super::*;              // bring the parent module into scope

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

    #[test]
    fn can_test_private_functions() {
        assert_eq!(internal_helper(3), 6);    // child modules see private items
    }
}

Run with cargo test. A test passes if it returns without panicking.

Assertions

rust
assert!(condition);
assert!(condition, "custom message with {value}");
assert_eq!(a, b);              // prints both values on failure
assert_ne!(a, b);
debug_assert!(condition);      // compiled out in release builds

assert_eq! requires PartialEq and Debug on the operands — one more reason to derive both on your types.

Testing failure

rust
#[test]
#[should_panic]
fn panics_on_bad_input() {
    divide(1, 0);
}

#[test]
#[should_panic(expected = "division by zero")]
fn panics_with_the_right_message() {      // substring match — more precise
    divide(1, 0);
}

Tests returning Result

rust
#[test]
fn parses_config() -> Result<(), Box<dyn std::error::Error>> {
    let cfg = parse("port=8080")?;        // `?` works — an Err fails the test
    assert_eq!(cfg.port, 8080);
    Ok(())
}

You can't use #[should_panic] on these; use assert!(result.is_err()) instead.

Other attributes

rust
#[test]
#[ignore]                    // skipped unless you pass --ignored
fn expensive_test() {}

The anatomy of a Rust test

rust
pub fn add(a: i32, b: i32) -> i32 { a + b }

#[cfg(test)]                       // only compile this when testing
mod tests {
    use super::*;                  // bring the parent module's items into scope

    #[test]                        // this function is a test
    fn adds_two_positive_numbers() {
        assert_eq!(add(2, 3), 5);
    }

    #[test]
    fn returns_error_for_bad_input() {
        let result = parse_age("abc");
        assert!(result.is_err());
    }

    #[test]
    #[should_panic(expected = "divide by zero")]
    fn panics_on_zero() {
        divide(1, 0);
    }
}

Each annotation earns its place:

  • #[cfg(test)] means the whole module is skipped in normal builds. Your tests add nothing to the shipped binary.
  • use super::*; imports everything from the module being tested — which is why unit tests can reach private functions.
  • #[test] marks a test. It takes no arguments; it passes if it returns without panicking.
  • #[should_panic(expected = "...")] inverts that: the test passes only if it panics, and only if the message contains that text. The expected part matters — without it, a panic for a completely different reason still counts as a pass.

The assertion macros: assert!(condition), assert_eq!(a, b), assert_ne!(a, b). Prefer assert_eq! where you can — it prints both values on failure, which usually tells you what went wrong without a debugger.

Analogy — the bench test and the road test

A unit test is a bench test: one part, isolated, wired to a rig, run in seconds. An integration test drives the assembled car around the block using only the controls a driver has. You need both, and confusing them is how suites end up slow and untrustworthy — a bench test that needs the whole car is neither fast nor precise.

16.2 Running tests

bash
cargo test                       # everything
cargo test add                   # only tests whose name contains "add"
cargo test tests::adds_two       # exact path
cargo test -- --ignored          # only ignored tests
cargo test -- --include-ignored  # everything including ignored
cargo test -- --nocapture        # show println! output from passing tests
cargo test -- --test-threads=1   # run serially (useful for shared state/files)
cargo test --lib                 # unit tests only
cargo test --test integration    # one integration test file
cargo test --doc                 # documentation tests only

Tests run in parallel by default, each in its own thread. This means tests that share a file, a database, or an environment variable will flake. Either give each test its own resource (a temp dir named after the test) or serialize with --test-threads=1.

16.3 Integration tests

myproject/
├── src/
│   └── lib.rs
└── tests/
    ├── common/
    │   └── mod.rs           # shared helpers (NOT a test file itself)
    └── api_test.rs          # its own crate
rust
// tests/api_test.rs
use myproject::{add, Config};      // only the PUBLIC api is visible

mod common;

#[test]
fn end_to_end() {
    common::setup();
    assert_eq!(add(2, 2), 4);
}

Each file in tests/ is compiled as a separate crate that links your library as an external dependency. That's the point: integration tests exercise your crate exactly the way a user would, catching accidental privacy of items you meant to export.

Note common/mod.rs rather than common.rs — a top-level tests/common.rs would be treated as its own test crate and show up as an empty test run.

Note

Integration tests can't test binaries directly. This is the practical reason for the lib + thin main split from module 10.


Unit or integration? A test you can apply

Put a test in tests/ when you can answer yes to: could a user of my crate write this test?

text
my_crate/
├── src/
│   └── lib.rs          unit tests live here, in `mod tests`
└── tests/
    └── api.rs          integration tests — a separate crate
rust
// tests/api.rs — no #[cfg(test)] needed; the whole file only builds for tests
use my_crate::Parser;    // only PUBLIC items are visible here

#[test]
fn parses_a_full_document() {
    let doc = Parser::new().parse("title: hello").unwrap();
    assert_eq!(doc.title, "hello");
}

Why keeping both matters:

  • Unit tests are fast, precise, and can test the awkward internal branch you cannot reach from outside. When one fails you know exactly which function is wrong.
  • Integration tests catch a different class of problem entirely: the type you forgot to make pub, the API that is technically correct and unusable, the module reorganisation that broke everyone's imports. They fail the way your users would.

A codebase with only unit tests ships broken public APIs. One with only integration tests takes ages to run and cannot tell you where the bug is.

16.4 Documentation tests

Code blocks in doc comments are compiled and run by cargo test:

rust
/// Adds two numbers together.
///
/// # Examples
///
/// ```
/// use mycrate::add;
/// assert_eq!(add(2, 3), 5);
/// ```
///
/// Errors are shown too:
///
/// ```should_panic
/// mycrate::divide(1, 0);
/// ```
///
/// Hide setup lines with a leading `#`:
///
/// ```
/// # use mycrate::Config;
/// let c = Config::new();
/// assert!(c.is_valid());
/// ```
///
/// Don't run this one, just check it compiles:
///
/// ```no_run
/// mycrate::start_server();
/// ```
///
/// Don't even compile:
///
/// ```ignore
/// this is pseudocode
/// ```
pub fn add(a: i32, b: i32) -> i32 { a + b }

This is Rust's best documentation feature: examples in your docs cannot go stale, because CI compiles and runs them.

Doc comment conventions

rust
/// One-line summary, imperative mood.
///
/// Longer explanation.
///
/// # Examples
/// # Panics
/// # Errors
/// # Safety          (required for `unsafe fn`)

//! documents the enclosing item — put a crate-level overview at the top of lib.rs.


Analogy — documentation with a smoke test attached

Every code example in every README you have read is a promise nobody verified. A Rust doc test is that same example wired to the build: if the API changes and the example stops compiling, the build goes red. You are not writing docs and tests; you are writing one artefact that cannot silently rot.

16.5 Tooling

rustfmt

bash
cargo fmt              # format everything
cargo fmt -- --check   # fail if unformatted (use in CI)

Configure with rustfmt.toml, but the community norm is to leave it at defaults. Arguing about formatting is a solved problem in Rust.

clippy

bash
cargo clippy                        # lint
cargo clippy --all-targets          # include tests and examples
cargo clippy -- -D warnings         # treat warnings as errors (CI)
cargo clippy --fix                  # auto-apply safe suggestions

Clippy is a teacher. Typical lessons:

rust
if x == true { }                    // clippy: use `if x`
v.iter().map(|x| x).collect()       // clippy: redundant closure
s.len() == 0                        // clippy: use `is_empty()`
match x { Some(v) => f(v), None => {} }   // clippy: use `if let`
&String parameter                   // clippy: use `&str`

Silence a specific lint when you're sure:

rust
#[allow(clippy::too_many_arguments)]
fn complicated(/* ... */) {}

Other cargo subcommands worth installing

bash
cargo install cargo-watch      # cargo watch -x check -x test
cargo install cargo-edit       # cargo add/rm/upgrade
cargo install cargo-audit      # scan dependencies for security advisories
cargo install cargo-nextest    # much faster, better test runner
cargo install cargo-expand     # see what macros expand to
cargo install cargo-llvm-cov   # code coverage
cargo install cargo-outdated   # list outdated deps
cargo install flamegraph       # profiling

Clippy as a teacher, not a nag

cargo clippy is the fastest way to learn idiomatic Rust, because it names the idiom you were missing:

rust
// You wrote:
let mut total = 0;
for n in &numbers {
    total += n;
}

// clippy: this loop could be written as a `sum()`
let total: i32 = numbers.iter().sum();

It catches hundreds of these — needless clone(), a match that wants if let, comparing to true, manual Option handling that has a method. Treat each warning as a small lesson rather than an annoyance, and your Rust will read like Rust within a month.

The workflow worth adopting now, before you have habits to unlearn:

bash
cargo fmt                      # format — no arguments, no preferences, done
cargo clippy -- -D warnings    # lint, and treat every warning as an error
cargo test                     # unit + integration + doc tests

Run those three before every commit, and put the same three in CI (§16.7). The -D warnings part is what makes it real: a warning nobody must fix is a warning everybody ignores.

Analogy — the pedant you are glad to have

rustfmt ends every formatting argument by taking the decision away from everyone. clippy is the colleague who has read the entire standard library and cannot help pointing out that your six lines are one iter().sum() — irritating for a week, and then simply how you learn idiom.

16.6 Benchmarking

Stable Rust has no built-in benchmark harness. Use criterion:

toml
[dev-dependencies]
criterion = "0.5"

[[bench]]
name = "my_bench"
harness = false
rust
// benches/my_bench.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn fib(n: u64) -> u64 { if n < 2 { n } else { fib(n - 1) + fib(n - 2) } }

fn bench_fib(c: &mut Criterion) {
    c.bench_function("fib 20", |b| b.iter(|| fib(black_box(20))));
}

criterion_group!(benches, bench_fib);
criterion_main!(benches);
bash
cargo bench

black_box prevents the optimizer from deleting the computation because the result is unused. Criterion runs many iterations, reports confidence intervals, and compares against the previous run — it will tell you "performance has improved by 12%".

16.7 A CI baseline

yaml
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy
      - uses: Swatinem/rust-cache@v2
      - run: cargo fmt --all -- --check
      - run: cargo clippy --all-targets -- -D warnings
      - run: cargo test --all-features
      - run: cargo doc --no-deps

Four commands. That's a solid Rust CI, and it catches formatting drift, lint regressions, broken tests, broken doc examples, and broken doc links.

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
unit testA test inside the module it tests, able to see private items.
integration testA test in tests/, compiled separately, seeing only the public API.
doc testA code example in a /// comment, compiled and run by cargo test.
#[cfg(test)]Compile this only when testing, so it never ships.
#[test]Marks a function as a test.
#[should_panic]The test passes only if the code panics.
assertionA check that fails the test when false: assert!, assert_eq!.
#[ignore]Skip this test unless explicitly requested with --ignored.
test harnessThe runner Cargo builds around your tests, which runs them in parallel by default.
rustfmtThe official formatter. No configuration arguments.
clippyThe official linter, with hundreds of idiom and correctness lints.
benchmarkA timed performance test — via criterion on stable Rust.
CIContinuous integration: the same checks, run automatically on every push.

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
cannot find function in this scope inside mod testsThe test module cannot see the parent's items.Add use super::*; at the top of the module.
An integration test cannot see your functionIt is not public, or not re-exported.Mark it pub, and check it is reachable from the crate root.
Tests pass individually but fail togetherThey share state — a file, an env var, a global.Give each test its own resource, or serialise them with a crate like serial_test.
test did not panic as expected#[should_panic] on code that succeeded.Check the input actually triggers the panic, and that expected matches the message.
Doc test fails but the code is fineThe example itself is out of date.Update the example — that failure is the feature working.

Now make it stick: work through the drills for this module, then carry on to Module 17 — Fearless Concurrency.