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
