Testing

As we know testing is integral to any piece of software! Rust has first-class
support for unit and integration testing (see this
chapter
in
TRPL).

From the testing chapters linked above, we see how to write unit tests and
integration tests. Organizationally, we can place unit tests in the modules they
test and integration tests in their own tests/ directory:

  1. foo
  2. ├── Cargo.toml
  3. ├── src
  4. └── main.rs
  5. └── tests
  6. ├── my_test.rs
  7. └── my_other_test.rs

Each file in tests is a separate integration test.

cargo naturally provides an easy way to run all of your tests!

  1. cargo test

You should see output like this:

  1. $ cargo test
  2. Compiling blah v0.1.0 (file:///nobackup/blah)
  3. Finished dev [unoptimized + debuginfo] target(s) in 0.89 secs
  4. Running target/debug/deps/blah-d3b32b97275ec472
  5. running 3 tests
  6. test test_bar ... ok
  7. test test_baz ... ok
  8. test test_foo_bar ... ok
  9. test test_foo ... ok
  10. test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

You can also run tests whose name matches a pattern:

  1. cargo test test_foo
  1. $ cargo test test_foo
  2. Compiling blah v0.1.0 (file:///nobackup/blah)
  3. Finished dev [unoptimized + debuginfo] target(s) in 0.35 secs
  4. Running target/debug/deps/blah-d3b32b97275ec472
  5. running 2 tests
  6. test test_foo ... ok
  7. test test_foo_bar ... ok
  8. test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out

One word of caution: Cargo may run multiple tests concurrently, so make sure
that they don’t race with each other. For example, if they all output to a
file, you should make them write to different files.