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




















































