liveBook · Manning

Rust testing system

As explained in Refactoring to Rust

The Rust test framework is the component that discovers tests, executes them, captures output, and reports their results.

Rust marks test functions with #[test] inside a #[cfg(test)] module. The test framework discovers them, runs them, captures output, and reports passing or failing results. section 7.1

A basic Rust test combines:

  • A function containing the behavior under test. section 7.1
  • The #[test] attribute, which identifies the function as a test. section 7.1
  • Assertions such as assert_eq! and assert!, which panic when expectations fail. section 7.1
  • cargo test, which compiles and runs tests and summarizes their results. section 7.1

A passing test

Place a test in a conditional test module: calculate 2 + 2, then use assert_eq!(result, 4). If the values differ, the test thread panics and the framework reports failure with both values. section 7.1

Listing 7.1 Contents of a newly initialized Rust library
#[cfg(test)]
mod tests {
  #[test]
  fn it_works() {
    let result = 2 + 2;
    assert_eq!(result, 4);
  }
}

Inspect the complete initialized library test module, including #[cfg(test)], #[test], and assert_eq!. section 7.1

$ cargo test -- --nocapture --test-threads=1
    Finished test [unoptimized + debuginfo] target(s) in 0.03s
     Running unittests

running 2 tests
test tests::it_does_not_work ... it_does_not_work stderr
it_does_not_work stdout
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `4`,
 right: `5`', chapter-07/listing_03_stdout/src/lib.rs:16:5
note: run with `RUST_BACKTRACE=1` environment variable to display backtrace
FAILED
test tests::it_works ... it_works stderr
it_works stdout
ok

failures:

failures:
    tests::it_does_not_work

test result: FAILED. 1 passed; 1 failed;

Compare serialized test output by disabling capture and forcing a single test thread. section 7.1

How Refactoring to Rust covers it

How deep it goes
Explains test attributes, assertions, panic handling, captured output, and reporting without descending into framework internals.
Examples
Uses arithmetic tests, deliberate assertion failures, captured output, and cargo test command variations.
What it assumes
Assumes basic Rust functions and modules while introducing test attributes and assertion macros through small examples.
What you can do after
Apply it via Cargo to write, run, inspect, and diagnose basic Rust unit tests.
How it connects
Connects test modules with functions, attribute macros, assertions, panics, stdout, stderr, and Cargo.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.