Skip to main content

Programming languages · Intermediate · 24 min

Test Rust code with unit, integration and doc tests

By Padding · Updated 18 Nov 2026
Debian (rust:1.100 image) · Rust 1.100.0 · Cargo 1.100.0 · proptest 1.12.0

You will test a small Rust invoice library with unit tests that reach private code, integration tests that see only the public API, doc tests that keep its examples honest and a proptest property that finds a formatting bug the other tests missed.

On this page

Rust has testing built into the language and Cargo. #[test] marks a test function, cargo test builds and runs every test in the package, and there is nothing to install for the basics. What takes practice is knowing which of Rust's three kinds of test to write:

  • Unit tests live next to the code in a #[cfg(test)] module. They are part of the crate, so they can call private functions.
  • Integration tests live in a tests/ folder. Each file is compiled as a separate crate that uses yours from outside, so they can only touch what you made pub.
  • Doc tests are the code examples in your /// comments. cargo test compiles and runs them, so an example that stops working fails the build instead of misleading the next reader.

You build invoice, a library that adds up invoice lines, applies VAT and formats amounts as text. Money is stored as whole numbers of minor units (kobo, cents, pesewas), so 150,075 means 1500.75 and no floating-point rounding creeps in. The first version has a bug that none of the hand-written tests catch. In the last part, a property test with the proptest crate finds it, shrinks it to a small example and saves it so it cannot come back.

Everything was written for Rust 1.100.0 and the 2024 edition. Any Rust from 1.88 onwards runs it, because that is the oldest version proptest 1.12 supports.

Step 1 · Write the invoice library

Create a library crate in a throwaway folder. --lib makes a library instead of a program, and --vcs none skips creating a Git repository:

Bash
cargo new --lib --vcs none ~/invoice-demo --name invoice
cd ~/invoice-demo

Replace src/lib.rs with the invoice types. Read the doc comment on Invoice: the code block inside it is an example now and a test in a moment.

Bash
cat > src/lib.rs <<'RS'
//! Invoice maths for small businesses. Amounts are whole numbers of
//! minor units (kobo, cents, pesewas): 150_075 means 1500.75.

use std::fmt;

mod money;
pub use money::{format_amount, parse_amount};

/// One line on an invoice.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LineItem {
    pub description: String,
    /// Price of one unit in minor units.
    pub unit_price: u64,
    pub quantity: u32,
}

/// Why an invoice operation failed.
#[derive(Debug, PartialEq, Eq)]
pub enum InvoiceError {
    /// The invoice has no lines.
    NoItems,
    /// A line was added with a quantity of zero.
    ZeroQuantity(String),
    /// Text that is not an amount such as `12.50`.
    BadAmount(String),
}

impl fmt::Display for InvoiceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            InvoiceError::NoItems => write!(f, "the invoice has no items"),
            InvoiceError::ZeroQuantity(d) => write!(f, "quantity for {d:?} is zero"),
            InvoiceError::BadAmount(t) => write!(f, "{t:?} is not an amount"),
        }
    }
}

impl std::error::Error for InvoiceError {}

/// Line items plus a VAT rate in basis points (750 basis points = 7.5%).
///
/// ```
/// use invoice::Invoice;
///
/// let mut inv = Invoice::new(750);
/// inv.add("Logo design", 5_000_000, 1).unwrap();
/// inv.add("Business cards", 1_250, 200).unwrap();
/// assert_eq!(inv.subtotal(), 5_250_000);
/// assert_eq!(inv.vat(), 393_750);
/// assert_eq!(inv.total().unwrap(), 5_643_750);
/// ```
#[derive(Debug)]
pub struct Invoice {
    items: Vec<LineItem>,
    vat_bp: u32,
}

impl Invoice {
    /// Starts an empty invoice. Panics if the VAT rate is above 100%.
    pub fn new(vat_bp: u32) -> Self {
        assert!(vat_bp <= 10_000, "VAT rate above 100%: {vat_bp} basis points");
        Invoice { items: Vec::new(), vat_bp }
    }

    /// Adds a line. A quantity of zero is an error.
    pub fn add(&mut self, description: &str, unit_price: u64, quantity: u32) -> Result<(), InvoiceError> {
        if quantity == 0 {
            return Err(InvoiceError::ZeroQuantity(description.to_string()));
        }
        self.items.push(LineItem { description: description.to_string(), unit_price, quantity });
        Ok(())
    }

    /// The lines added so far.
    pub fn items(&self) -> &[LineItem] {
        &self.items
    }

    /// Unit price times quantity, summed over every line.
    pub fn subtotal(&self) -> u64 {
        self.items.iter().map(|i| i.unit_price * u64::from(i.quantity)).sum()
    }

    /// VAT on the subtotal, rounded to the nearest minor unit.
    pub fn vat(&self) -> u64 {
        percent_of(self.subtotal(), self.vat_bp)
    }

    /// Subtotal plus VAT. An invoice with no lines is an error.
    pub fn total(&self) -> Result<u64, InvoiceError> {
        if self.items.is_empty() {
            return Err(InvoiceError::NoItems);
        }
        Ok(self.subtotal() + self.vat())
    }
}

/// `amount` times `bp` basis points, with halves rounded up. Private.
fn percent_of(amount: u64, bp: u32) -> u64 {
    let scaled = u128::from(amount) * u128::from(bp) + 5_000;
    (scaled / 10_000) as u64
}
RS

percent_of has no pub, so only code inside this crate can call it. It works in u128 so that a large amount times a rate cannot overflow before the division.

The amount text functions go in their own module file. Each has an example in its doc comment:

Bash
cat > src/money.rs <<'RS'
use crate::InvoiceError;

/// Writes an amount in minor units as `major.minor` text.
///
/// ```
/// assert_eq!(invoice::format_amount(150_075), "1500.75");
/// ```
pub fn format_amount(minor: u64) -> String {
    format!("{}.{}", minor / 100, minor % 100)
}

/// Reads text such as `12.50`, `12.5` or `12` into minor units.
///
/// ```
/// use invoice::parse_amount;
///
/// assert_eq!(parse_amount("12.50"), Ok(1_250));
/// assert_eq!(parse_amount("12.5"), Ok(1_250));
/// assert!(parse_amount("-3").is_err());
/// ```
pub fn parse_amount(text: &str) -> Result<u64, InvoiceError> {
    let bad = || InvoiceError::BadAmount(text.to_string());
    let (major, minor) = text.split_once('.').unwrap_or((text, ""));
    let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit());
    if major.is_empty() || minor.len() > 2 || !digits(major) || !digits(minor) {
        return Err(bad());
    }
    let major: u64 = major.parse().map_err(|_| bad())?;
    let minor: u64 = match minor.len() {
        0 => 0,
        1 => minor.parse::<u64>().map_err(|_| bad())? * 10,
        _ => minor.parse().map_err(|_| bad())?,
    };
    major.checked_mul(100).and_then(|m| m.checked_add(minor)).ok_or_else(bad)
}
RS

Build it, then run cargo test once before writing a single test:

Bash
cargo build
cargo test

Check it worked

cargo build ends with a Finished line and no warnings. cargo test prints two groups. The first, unittests src/lib.rs, says running 0 tests. The second, Doc-tests invoice, runs 3 tests (one per code block in the doc comments) and ends with test result: ok. 3 passed; 0 failed. Your examples are already being checked.

Step 2 · Add unit tests that reach private code

Unit tests go at the bottom of the file they test, in a module marked #[cfg(test)]. That attribute means the module is compiled only for cargo test, so test code never ends up in your release build. Because the module is a child of the crate root, use super::* brings in everything, private percent_of included.

Append the module to src/lib.rs:

Bash
cat >> src/lib.rs <<'RS'

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

    #[test]
    fn percent_of_rounds_half_up() {
        // 7.5% of 1 is 0.075: rounds down to 0.
        assert_eq!(percent_of(1, 750), 0, "tiny amounts round down");
        // 7.5% of 20 is 1.5: rounds up to 2.
        assert_eq!(percent_of(20, 750), 2, "a half rounds up");
        assert_eq!(percent_of(5_250_000, 750), 393_750);
    }

    #[test]
    fn percent_of_does_not_overflow() {
        assert_eq!(percent_of(u64::MAX, 10_000), u64::MAX);
    }

    #[test]
    fn zero_quantity_is_rejected() {
        let mut inv = Invoice::new(0);
        let err = inv.add("Delivery", 2_000, 0).unwrap_err();
        assert_eq!(err, InvoiceError::ZeroQuantity("Delivery".into()));
        assert!(inv.items.is_empty(), "nothing should be added, got {:?}", inv.items);
    }

    #[test]
    #[should_panic(expected = "VAT rate above 100%")]
    fn vat_over_100_percent_panics() {
        Invoice::new(10_001);
    }

    #[test]
    fn total_of_parsed_prices() -> Result<(), InvoiceError> {
        let mut inv = Invoice::new(750);
        inv.add("Printing", parse_amount("125.40")?, 3)?;
        assert_eq!(inv.total()?, 40_442);
        Ok(())
    }
}
RS

Each test shows a different tool:

  • assert_eq! with a message. Anything after the two values is a format string. When the assertion fails, Rust prints the left value, the right value and your message, so a failure says what rule broke rather than only that two numbers differ.
  • Private access. percent_of and the private items field are reachable here and nowhere outside the crate.
  • #[should_panic(expected = "...")] passes only if the test panics with a message containing that text. Without expected, any panic would pass, including one from a typo in the test.
  • A test that returns Result. You can use ? inside it. If any ? meets an Err, the test fails and prints the error. In total_of_parsed_prices, 3 × 125.40 is 376.20, 7.5% VAT on that is 28.215, which rounds to 28.22, so the total is 404.42, or 40,442 minor units.

Run only the unit tests with --lib:

Bash
cargo test --lib

Check it worked

The output lists five tests, each ending in ok, such as test tests::vat_over_100_percent_panics - should panic ... ok, then test result: ok. 5 passed; 0 failed. The doc tests did not run, because --lib selects only the library's own test build.

Step 3 · Add integration tests that use only the public API

Files in tests/ are compiled as separate crates that depend on invoice like any other user would. They import it by name and see only pub items. If you tried invoice::percent_of(1, 750) here, the build would stop with an error saying the function is private. That limit is useful: these tests break only when the public behaviour changes, not when you rearrange internals.

Bash
mkdir -p tests
cat > tests/invoice_api.rs <<'RS'
use invoice::{format_amount, Invoice, InvoiceError};

fn sample() -> Invoice {
    let mut inv = Invoice::new(750);
    inv.add("Logo design", 5_000_000, 1).unwrap();
    inv.add("Business cards", 1_250, 200).unwrap();
    inv
}

#[test]
fn total_includes_vat() {
    let inv = sample();
    assert_eq!(inv.total(), Ok(5_643_750));
    assert_eq!(format_amount(inv.total().unwrap()), "56437.50");
}

#[test]
fn empty_invoice_has_no_total() {
    assert_eq!(Invoice::new(750).total(), Err(InvoiceError::NoItems));
}

#[test]
fn prints_a_summary() {
    let inv = sample();
    for item in inv.items() {
        println!("{:<16} {:>4} x {}", item.description, item.quantity, format_amount(item.unit_price));
    }
    assert_eq!(inv.items().len(), 2);
}

#[test]
#[ignore = "stress test: adds 200,000 lines"]
fn large_invoice_adds_up() {
    let mut inv = Invoice::new(750);
    for n in 0..200_000u64 {
        inv.add("Bulk line", n % 1_000 + 1, 1).unwrap();
    }
    // Prices cycle through 1..=1000, which sums to 500,500, 200 times over.
    assert_eq!(inv.subtotal(), 200 * 500_500);
}
RS

The helper sample() has no #[test], so it is ordinary code the tests share. The last test is marked #[ignore]. Tests that take seconds or minutes (large inputs, slow stand-ins for other systems) make every cargo test slower, so you keep them out of the everyday run and run them on purpose. This one is quick, but it stands in for one that is not.

Run only this file with --test and its name, then the ignored test on its own, then everything:

Bash
cargo test --test invoice_api
cargo test --test invoice_api -- --ignored
cargo test -- --include-ignored

Everything after -- goes to the test runner rather than to Cargo. --ignored runs only ignored tests; --include-ignored runs both kinds.

Check it worked

The first command reports test large_invoice_adds_up ... ignored, stress test: adds 200,000 lines and ends 3 passed; 0 failed; 1 ignored. The second runs only large_invoice_adds_up and reports 1 passed. The third runs every group (unit, integration and doc tests) and no group says ignored with a number above 0.

Step 4 · Write doc tests that keep the examples honest

You already have three doc tests. Add a module that builds a plain-text receipt, with examples that show three more features of doc tests: hidden lines, ? inside an example, and an example that must not compile.

Bash
cat > src/receipt.rs <<'RS'
//! Plain-text receipts.
//!
//! The VAT helper is private, so outside code cannot call it:
//!
//! ```compile_fail
//! invoice::percent_of(100, 750);
//! ```

use crate::{format_amount, Invoice, InvoiceError};

/// One line per item, then the VAT, then the total.
///
/// ```
/// use invoice::{receipt::receipt, Invoice};
/// # fn main() -> Result<(), invoice::InvoiceError> {
/// let mut inv = Invoice::new(750);
/// inv.add("Hosting", 1_234_560, 1)?;
/// let text = receipt(&inv)?;
/// assert_eq!(text.lines().last(), Some("TOTAL 13271.52"));
/// # Ok(())
/// # }
/// ```
///
/// An invoice with no lines has no receipt:
///
/// ```
/// let empty = invoice::Invoice::new(750);
/// assert!(invoice::receipt::receipt(&empty).is_err());
/// ```
pub fn receipt(inv: &Invoice) -> Result<String, InvoiceError> {
    let total = inv.total()?;
    let mut out = String::new();
    for item in inv.items() {
        out.push_str(&format!("{} x{} {}\n", item.description, item.quantity, format_amount(item.unit_price)));
    }
    out.push_str(&format!("VAT {}\n", format_amount(inv.vat())));
    out.push_str(&format!("TOTAL {}", format_amount(total)));
    Ok(out)
}
RS
cat >> src/lib.rs <<'RS'

pub mod receipt;
RS

How these examples work:

  • Each fenced block is one test. rustdoc wraps it in a small program that depends on your crate, so examples use the public path (invoice::receipt::receipt), exactly as a reader would.
  • Lines starting with `# ` are hidden. They are compiled and run, but cargo doc leaves them out of the rendered page. Here they wrap the example in a main that returns Result, so the visible lines can use ? the way real code does.
  • compile_fail passes only if the block fails to compile. It documents what users cannot do. Keep these short: any compile error counts, including a typo, so a long one can pass for the wrong reason.
  • Two more markers you will meet: no_run compiles an example but does not run it (useful for code that would open a network connection), and ignore skips it entirely. Prefer no_run to ignore, so the example at least keeps compiling.

Run only the doc tests:

Bash
cargo test --doc

Check it worked

The output names each example by file and item, such as src/receipt.rs - receipt::receipt (line 13) ... ok, with a line number that depends on your file. In the 2024 edition rustdoc merges ordinary examples into one test program, so they report together as test result: ok. 5 passed; 0 failed. The compile_fail block cannot be merged, so it runs in a second group of its own, shows - compile fail ... ok and reports 1 passed: six doc tests in all. To see what a stale example looks like, change 13271.52 in src/receipt.rs to 13271.53 and run cargo test --doc again: the doc test fails and prints both values. Change it back before you go on.

Step 5 · Pick which tests run and see their output

As a suite grows you run a slice of it while you work. cargo test takes a filter: any test whose full name contains the text runs, and the rest are counted as filtered out.

Bash
cargo test percent
cargo test --lib -- --exact tests::zero_quantity_is_rejected
cargo test --lib -- --list

The first runs the two percent_of tests, and also vat_over_100_percent_panics, because the filter matches anywhere in the name. --exact matches the full name only, so a filter of tests::zero would match nothing. --list prints test names without running them, which is how you find the full name to paste.

By default the runner captures what passing tests print, so a green run stays quiet. To see println! output, ask for it:

Bash
cargo test --test invoice_api prints_a_summary -- --nocapture
cargo test --test invoice_api prints_a_summary -- --show-output

--nocapture lets output through as it happens, mixed in with the runner's own lines. --show-output keeps it captured and prints it in a block after the results, which is easier to read when several tests print. If output from tests running in parallel gets interleaved, add --test-threads=1 to run them one at a time. That also helps on a laptop with little memory.

Check it worked

cargo test percent shows test tests::percent_of_does_not_overflow ... ok, test tests::percent_of_rounds_half_up ... ok and the vat_over_100_percent_panics test, with 3 passed and 2 filtered out in the unit test group. The --exact run reports 1 passed. Both summary runs print two lines, something like:

Text
Logo design         1 x 50000.0
Business cards    200 x 12.50

Look at the first price. A logo design at 50,000 should read 50000.00, not 50000.0. Every test passes, yet the output is wrong. The next step finds out why without guessing.

Step 6 · Let a property test find the edge case

Every test so far checks examples you thought of. A property test states a rule that should hold for every input, then tries hundreds of generated inputs to break it. A good rule for format_amount is the round trip: formatting an amount and parsing the text back must give the original amount.

Add proptest as a dev-dependency, which is compiled for tests only:

Bash
cargo add --dev proptest@1.12.0

Write the properties in their own file and include it from src/lib.rs for tests only:

Bash
cat > src/properties.rs <<'RS'
use proptest::prelude::*;

use crate::{format_amount, parse_amount};

proptest! {
    #[test]
    fn format_then_parse_gives_the_same_amount(amount in 0u64..10_000_000_000) {
        let text = format_amount(amount);
        prop_assert_eq!(parse_amount(&text), Ok(amount), "formatted as {}", text);
    }

    #[test]
    fn parse_never_panics(text in "\\PC{0,12}") {
        let _ = parse_amount(&text);
    }
}
RS
cat >> src/lib.rs <<'RS'

#[cfg(test)]
mod properties;
RS

amount in 0u64..10_000_000_000 tells proptest to draw amounts from that range. "\\PC{0,12}" is a regular expression strategy: up to 12 printable characters from anywhere in Unicode, so the second property feeds the parser accents, Arabic or Amharic script and emoji, not only digits. Both properties run 256 cases by default.

Run them:

Bash
cargo test --lib properties

Check it worked

parse_never_panics passes. format_then_parse_gives_the_same_amount fails with a message something like Test failed: assertion failed: left == right ... formatted as 0.5; minimal failing input: amount = 5. The exact amount varies between runs, but it always ends in 01 to 09.

proptest did two things here. First it found a failing amount among random ones, probably a large and messy number. Then it shrank it, trying smaller and simpler values that still fail, until it reached the small one it reports. That is the bug: format!("{}.{}", ...) writes 5 minor units as 0.5, which parses back as 50. The same mistake turned 5,000,000 into 50000.0 in the previous step. The only doc example used 150,075, whose last two digits happen to be 75, so it passed.

ls proptest-regressions shows a file called properties.txt. proptest saved the failing case there.

Step 7 · Fix the bug and keep the regression

The fix is to pad the minor part to two digits with {:02}. Rewrite src/money.rs, and add the cases that would have caught the bug to the doc example, so the documentation shows them too:

Bash
cat > src/money.rs <<'RS'
use crate::InvoiceError;

/// Writes an amount in minor units as `major.minor` text, always with
/// two digits after the point.
///
/// ```
/// assert_eq!(invoice::format_amount(150_075), "1500.75");
/// assert_eq!(invoice::format_amount(5), "0.05");
/// assert_eq!(invoice::format_amount(5_000_000), "50000.00");
/// ```
pub fn format_amount(minor: u64) -> String {
    format!("{}.{:02}", minor / 100, minor % 100)
}

/// Reads text such as `12.50`, `12.5` or `12` into minor units.
///
/// ```
/// use invoice::parse_amount;
///
/// assert_eq!(parse_amount("12.50"), Ok(1_250));
/// assert_eq!(parse_amount("12.5"), Ok(1_250));
/// assert!(parse_amount("-3").is_err());
/// ```
pub fn parse_amount(text: &str) -> Result<u64, InvoiceError> {
    let bad = || InvoiceError::BadAmount(text.to_string());
    let (major, minor) = text.split_once('.').unwrap_or((text, ""));
    let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit());
    if major.is_empty() || minor.len() > 2 || !digits(major) || !digits(minor) {
        return Err(bad());
    }
    let major: u64 = major.parse().map_err(|_| bad())?;
    let minor: u64 = match minor.len() {
        0 => 0,
        1 => minor.parse::<u64>().map_err(|_| bad())? * 10,
        _ => minor.parse().map_err(|_| bad())?,
    };
    major.checked_mul(100).and_then(|m| m.checked_add(minor)).ok_or_else(bad)
}
RS
cargo test --lib properties
cat proptest-regressions/properties.txt

The regression file starts with comments explaining what it is, followed by a line beginning cc, a long hash (the seed that recreates the failing input) and a comment such as # shrinks to amount = 5. Every later run of this property tries the saved cases first, before any random ones. Commit the proptest-regressions folder with your code, so the same case is checked on every machine and in CI.

To test harder before a release, raise the number of cases for one run. PROPTEST_CASES=10000 cargo test --lib properties tries 10,000 inputs per property.

Check it worked

Both properties pass: test result: ok. 2 passed; 0 failed with 5 filtered out. cat shows the cc line. The proptest result for the round trip now holds for all 256 amounts, including the saved one.

Step 8 · Run all three kinds together, then clean up

Run the whole suite once more, the way CI would:

Bash
cargo test
cargo test --test invoice_api prints_a_summary -- --nocapture

The first run downloaded proptest and its dependencies. On prepaid or metered data, run cargo fetch once while you are connected; after that cargo test --offline builds and tests without touching the network.

When you have finished, remove the demo. Your Rust install stays:

Bash
cd ~
rm -rf ~/invoice-demo

Check it worked

Before the clean-up, cargo test printed a group for each kind of test, every result ending ok:

  • unittests src/lib.rs: 7 passed (five unit tests and two properties)
  • tests/invoice_api.rs: 3 passed; 0 failed; 1 ignored
  • Doc-tests invoice: 5 passed for the merged examples, then 1 passed for the compile_fail block

The summary now prints Logo design 1 x 50000.00. After the rm, ls ~/invoice-demo reports No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.