Writing Automated Tests1
To run the tests:
$ cargo test --package automated-tests --lib -- tests --nocapture
running 1 test
As this chapter is mostly code intensive, I'll leave that to lib.rs
.
To avoid running tests in parallel, or to control the number of threads:
cargo test -- --test-threads=1
To show function output (i.e. println!
's):
cargo test -- --show-output
To run a single test by name:
cargo test smaller_cannot_hold_larger
To run a subset of tests by name:
cargo test smaller_
To ignore some tests unless specifically requested:
#[test]
#[ignore]
fn expensive_test() {}
# Runs only ignored tests.
cargo test -- --ignored
# Runs all tests, including ignored.
cargo test -- --include-ignored
Unit tests are written in the src
directly with the code they are testing:
#[cfg(tests)]
mod tests {
use super::*;
#[test]
fn it_works() {}
}
Integration tests are written in a directory next to src,
, tests
:
11-automated-tests
├── Cargo.lock
├── Cargo.toml
├── src
│ └── lib.rs
└── tests
└── integration_test.rs
cargo test --test integration_test
As you add more integration tests, you'll want to create more files in tests/
:
├── Cargo.lock
├── Cargo.toml
├── src
│ └── lib.rs
└── tests
├── common
│ └── mod.rs
└── integration_test.rs