liveBook · Manning

Test output capture

As explained in Refactoring to Rust

Test output capture is the practice of storing a test's standard output and error streams and emitting them selectively in test reports.

Test output capture stores a test’s stdout and stderr in memory, keeping successful test runs quiet and displaying captured output when a test fails. section 7.1

Rust’s test runner provides two practical modes:

  • Run `cargo test` to see captured output for failing tests, including diagnostic values and the assertion location. section 7.1
  • Run `cargo test -- --nocapture` to emit every test’s output, passing the flag to the test binary after Cargo’s argument separator. section 7.1
  • Expect output from parallel tests to become interleaved when capture is disabled; add `--test-threads=1` for ordered output. section 7.1

Selective versus complete output

A test that calls `println!` and `eprintln!` remains silent when it passes, while a failing test displays both streams under the captured stdout report. Disabling capture displays output from passing tests too, but concurrent tests can mix their messages. section 7.1

Listing 7.3 Writing to stdout and stderr from tests
#[cfg(test)]
mod tests {
  #[test]
  fn it_works() {
    eprintln!("it_works stderr");
    println!("it_works stdout");
    let result = 2 + 2;
    assert_eq!(result, 4);
  }

  #[test]
  fn it_does_not_work() {
    eprintln!("it_does_not_work stderr");
    println!("it_does_not_work stdout");
    let result = 2 + 2;
    assert_eq!(result, 5);
  }
}

Inspect the paired `println!` and `eprintln!` calls used to demonstrate captured test output. section 7.1

How Refactoring to Rust covers it

How deep it goes
Explains in-memory capture, failure reporting, disabling capture, and parallel-output interleaving.
Examples
Uses passing and failing tests with println!, eprintln!, assert_eq!, cargo test, and nocapture command output.
What it assumes
Assumes basic Rust test modules, assertions, and Cargo test commands.
What you can do after
Apply via Cargo test commands to select diagnostic output or inspect every test’s output.
How it connects
Connects standard output and standard error with the Rust test framework, Cargo, assertions, and parallel test execution.

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.