Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Attributes

The #[test] and #[should_panic] attributes

Reference for Rust unit tests: #[test] functions, #[should_panic] with expected messages, Result-returning tests, assert macros and the cfg(test) module.

#[test] marks a function as a test. When the crate is built with --test (which is what cargo test does), the compiler collects all such functions into a test harness, runs each one, and reports it as passed if it returns normally and failed if it panics. In a normal build the functions are not compiled at all.

#[should_panic] flips the expectation: the test passes only if the function panics. A test can also return Result<(), E>, in which case an Err counts as failure, which lets you use ? inside tests.

Rust
#[cfg(test)]
mod tests {
    #[test]
    fn adds() {
        assert_eq!(2 + 2, 4);
    }
}

Try it

The runner here compiles with plain rustc, not --test, so the #[test] functions below are not executed automatically. The examples call the same functions from main to show exactly what a test body does and which panics a harness would catch.

Rust Test bodies called by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust What should_panic watches for

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
#[test]
fn name() { /* body */ }

#[test]
fn name() -> Result<(), E> { /* may use ? */ Ok(()) }

#[test]
#[should_panic]
fn name() { /* must panic */ }

#[test]
#[should_panic(expected = "substring")]
fn name() { /* must panic with a message containing the substring */ }
Part Description
#[test] Marks a function with no parameters that returns () or a Result<(), E> where E: Debug (or any Termination type)
#[should_panic] Test passes only if it panics
expected = "text" The panic message must contain this substring

Errors and edge cases:

  • A test that returns Err fails and prints the error with {:?}.
  • #[should_panic] cannot be combined with a Result-returning test.
  • A test that panics for the wrong reason still passes if you give no expected text, which hides bugs; add one.

Usage notes

  • Where tests live. Unit tests sit in a #[cfg(test)] mod tests inside the source file and can see private items through use super::*;. Integration tests go in the crate's tests/ folder and use only the public API.
  • Run model. Each test runs on its own thread, in parallel by default; cargo test -- --test-threads=1 runs them one at a time. Output printed with println! is shown only for failing tests unless you pass --nocapture.
  • Assertions. assert!, assert_eq! and assert_ne! accept a custom message; debug_assert! is for debug builds only. Order the arguments as (actual, expected) consistently to make failure messages readable.
  • Selecting tests. cargo test name runs tests whose path contains name. Skip slow tests with #[ignore].
  • Doc tests. Code blocks in /// comments are compiled and run as tests too.
  • Custom harnesses. Tests do not need #[test] if you disable the harness in Cargo.toml, but ordinary projects never do.