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
