liveBook · Manning

Test

As explained in Refactoring to Rust

A test function is a Rust function registered as an automated test by the test framework.

When a working system is refactored in small steps, automated tests help check that the new code still fulfills the old code’s contract. Existing tests can be reused; a refactor is also a good reason to add tests where none exist. section 1.1

A Rust test function is an ordinary function marked `#[test]`, which registers it with the test framework. Tests conventionally live near the code they check, inside a `tests` module. Marking that module `#[cfg(test)]` keeps it out of ordinary library and executable builds. section 7.1 section 7.3

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);
  }
}

The Cargo-generated library puts one `#[test]` function inside a `#[cfg(test)]` module. Its `assert_eq!` call checks that `2 + 2` equals `4`. section 7.1

To run and inspect a test:

  • Run `cargo test` to compile, discover, and execute test functions. section 7.3
  • Use `assert_eq!` to compare an actual value with an expected value. A mismatch fails the test and reports both values. section 7.1
  • For debugging output, `cargo test -- --nocapture` shows test output; adding `--test-threads=1` avoids interleaved output from concurrent tests. section 7.1

Checking a JSON-summing function

A test calls `sum` with JSON containing a name and an integer, then asserts the expected total. The input `r#"{ "name": "Stokes Baker", "value": 954832 }"#` is a raw string, so its JSON quotation marks need no escapes. Further test functions check other names and values; `cargo test` runs all three. section 7.1.2

How Refactoring to Rust covers it

How deep it goes
Works through test-module scaffolding, conditional compilation, assertions, test runs, failures, output options, and additional cases.
Examples
Uses Cargo’s arithmetic test, a deliberately failing assertion, and JSON inputs checked against expected sums.
What it assumes
Starts with a Cargo-generated blank library and explains test attributes and modules before applying them to existing Rust code.
What you can do after
Build it from scratch with `#[test]` and `assert_eq!`, then run and inspect the tests with `cargo test`.
How it connects
Connects test functions to refactoring, conditional compilation, assertions, raw strings, and documentation tests.

Also explained in

Compare how 53 books explain test →

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.