Skip to the workspace
Pebellslearn by building
Testing  ›  Lesson

Unit Tests with #[test]

Unit & Integration Testing 15 minA #[test] function is a test run by the Rust test harness. Tests can assert results or return supported result types; #[cfg(test)] commonly keeps test-only modules out of normal builds.

rust / Unit Tests with #[test]

Explore each scene at your own pace.

01 · The rule

The rule

Unit Tests with #[test]

A #[test] function is a test run by the Rust test harness. Tests can assert results or return supported result types; #[cfg(test)] commonly keeps test-only modules out of normal builds.

Write a check that fails on a known defect, then verify the repaired behavior.

The late-fee rule changed: 10 per day, but never more than 200. You edit one line. Did you break the zero-days case? Rust has testing built into the language and into Cargo, so checking takes one command and no extra setup.

The rule

Tests sit beside the code; a test passes unless it panics.

// src/fees.rs
pub fn late_fee(days_late: u32) -> u32 {
    (days_late * 10).min(200)
}

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

    #[test]
    fn charges_ten_per_day() {
        assert_eq!(late_fee(3), 30);
    }

    #[test]
    fn nothing_when_on_time() {
        assert_eq!(late_fee(0), 0);
    }

    #[test]
    fn capped_at_two_hundred() {
        assert_eq!(late_fee(50), 200);
    }
}
  • #[cfg(test)] compiles the module only for cargo test, so it adds nothing to real builds.
  • use super::*; brings the parent module's items in. Because tests is a child module, it can test private functions too.
  • #[test] marks a function as a test. It passes if it returns normally and fails if it panics.

The assert macros panic with a helpful message when a check fails:

  • assert!(cond): the condition must be true.
  • assert_eq!(left, right) and assert_ne!(left, right): on failure they print both values.

Expected panics and Result. Suppose lend panics with the message "already on loan" when a book is already out:

#[test]
#[should_panic(expected = "already on loan")]
fn cannot_lend_twice() {
    let mut book = Book::new("Iron Tides", 380);
    book.lend();
    book.lend();
}

#[test]
fn parses_card() -> Result<(), std::num::ParseIntError> {
    assert_eq!("1042".parse::<u32>()?, 1042);
    Ok(())
}

Running them: cargo test runs every test (in parallel). cargo test capped runs only tests whose names contain "capped". Output printed by passing tests is hidden unless you add -- --nocapture.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.