Integration Tests in the tests Folder
Integration tests live in the tests folder, each file is compiled as a separate crate, and they can only use the library's public API, just as a real user would.
Exercise public behavior from outside the crate's internal module tree.
Unit tests prove each piece works alone. But does lending, then returning, then lending again work when the pieces are used together, through the same functions another program would call? That is the job of integration tests, and Cargo has a folder waiting for them.
The rule
Unit tests check the parts from inside; integration tests use the public API from outside.
Put integration tests in a tests folder beside src:
shelf/
├── Cargo.toml
├── src/
│ ├── lib.rs # the library: pub struct Library, ...
│ └── main.rs # a thin program that uses the library
└── tests/
├── lending.rs
└── common/
└── mod.rs # shared helpers, not a test file itself// tests/lending.rs
use shelf::Library;
#[test]
fn lend_then_return_then_lend_again() {
let mut lib = Library::new();
lib.add("Iron Tides");
assert!(lib.lend("Iron Tides", 1042).is_ok());
assert!(lib.lend("Iron Tides", 2001).is_err()); // already out
lib.give_back("Iron Tides");
assert!(lib.lend("Iron Tides", 2001).is_ok());
}What makes these different:
- Each file in
tests/is compiled as its own crate that depends on yours. It imports your library by name,use shelf::..., like any outside user. - So it can use only
pubitems. Private helpers are invisible. - No
#[cfg(test)]is needed; Cargo only builds this folder forcargo test. - They need a library crate (
src/lib.rs). A crate with onlysrc/main.rshas nothing to import, so keep logic inlib.rsand letmain.rscall it. - Helpers shared by several test files go in
tests/common/mod.rsand are loaded withmod common;. A plaintests/common.rswould be treated as a test file of its own.
cargo test runs unit tests, then each integration file, then documentation examples. cargo test --test lending runs just one file.