Sub topic 14
Integration tests against the public API
This chapter assumes you can write unit tests with #[cfg(test)], you know how pub controls visibility, and you have a package with a src/lib.rs. Unit tests check internals from inside the crate. Integration tests check the crate the way a user sees it, from the outside.
What an integration test is
An integration test is a Rust file in a tests directory placed next to src at the package root. Cargo compiles each file directly inside tests as its own separate crate. That crate links against your library like any other dependency.
This has three consequences:
- The test sees only items marked
puband reachable from the crate root. - You do not need
#[cfg(test)]. Cargo builds thetestsdirectory only forcargo test. - You import the library by its crate name, for example
use my_geometry::add;. Theuse super::*trick from unit tests does not apply.
A first integration test
Start with a small library. It has one public type, one public function, and one private function.
// src/lib.rs
pub struct Square(pub u32);
impl Square {
pub fn area(&self) -> u32 {
self.0 * self.0
}
}
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
s.parse()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_valid_port() {
assert_eq!(parse_port("8080").unwrap(), 8080);
}
}The private parse_port is tested in the unit test module. An integration test cannot reach it. The public items are available:
// tests/area.rs
use my_geometry::{add, Square};
#[test]
fn add_works_through_public_api() {
assert_eq!(add(10, 20), 30);
}
#[test]
fn square_area_is_side_squared() {
let s = Square(5);
assert_eq!(s.area(), 25);
}Run it with cargo test --test area. The name after --test is the file name without .rs.
If you add my_geometry::parse_port("1") to this file, the build fails with an error like `function parse_port is private. That failure is the point of integration tests. They confirm that the public surface is enough to do the job. If you cannot test a behavior without making something pub`, that is a signal to ask whether the API is missing something. It is not always a reason to widen visibility.
Binary-only packages cannot be imported
Cargo can only link a test crate against a library target. A package that has only src/main.rs has no library to import, so use my_package::something; fails in tests/.
The usual fix is to move the logic into src/lib.rs and keep main.rs as a thin wrapper:
// src/main.rs
use my_geometry::Square;
fn main() {
let side: u32 = std::env::args()
.nth(1)
.and_then(|s| s.parse().ok())
.unwrap_or(1);
println!("{}", Square(side).area());
}This is the main reason many projects have both a lib.rs and a main.rs. The library holds the testable code, and the binary has little left to get wrong.
You can still test the binary itself. Cargo sets the environment variable CARGO_BIN_EXE_<name> for integration tests, where <name> is the binary's name. It holds the path to the compiled executable:
// tests/cli.rs
use std::process::Command;
#[test]
fn cli_prints_area_of_argument() {
let output = Command::new(env!("CARGO_BIN_EXE_my_geometry"))
.arg("3")
.output()
.expect("failed to run binary");
assert!(output.status.success());
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "9");
}env! reads the variable at compile time, so a wrong binary name is a compile error and not a runtime surprise.
Sharing helper code between test files
Because every file in tests/ is its own crate, they cannot see each other. Shared setup code needs a place that Cargo does not treat as a test file.
A first attempt is tests/common.rs. Cargo compiles it as a test crate, so cargo test prints a Running tests/common.rs section with running 0 tests. That is noise.
The fix is to use the older directory style, tests/common/mod.rs. Cargo only treats files directly inside tests/ as test crates. Files in subdirectories are ignored unless something declares them as modules.
// tests/common/mod.rs
use my_geometry::Square;
pub fn unit_square() -> Square {
Square(1)
}// tests/shared_setup.rs
mod common;
#[test]
fn unit_square_has_area_one() {
assert_eq!(common::unit_square().area(), 1);
}Each test file that declares mod common; gets its own copy of the helper module. If one file does not use every helper, the compiler warns about dead code. You can silence that with #![allow(dead_code)] at the top of tests/common/mod.rs.
One crate or many
Each top-level file in tests/ costs a separate compile and link step. In a large project with dozens of files, this slows cargo test down. A common remedy is a single test crate with submodules:
// tests/integration/main.rs
mod common;
mod area;
mod ports;Cargo treats tests/integration/main.rs as one test crate called integration. You then run it with cargo test --test integration. The trade-off is that a failure to compile in one submodule blocks all of them. Separate files are better for clear isolation, and a single crate is better for build speed.
How they fit in the test run
cargo test runs the test kinds in a fixed order:
- Unit tests, inside the library and binary crates.
- Integration tests, one
tests/crate at a time. - Documentation tests.
If any stage fails, Cargo stops and skips the later stages. Run cargo test --no-fail-fast to see failures from every stage in one run.
| Aspect | Unit test | Integration test |
|---|---|---|
| Location | Inside `src`, next to the code | `tests/` directory |
| Sees private items | Yes, through `use super::*` | No |
| Compiled as | Part of the crate under test | A separate crate |
| Needs `#[cfg(test)]` | Yes | No |
| Best for | Internal logic and edge cases | Workflows through the public API |
Common errors
unresolved importfor your crate. The package has nolib.rs, or the crate name uses a hyphen. A package namedmy-geometryis imported asmy_geometry.- A
common.rsfile shows up as a test target. Move it totests/common/mod.rs. - A function "is private". The test is reaching for something the public API does not expose. Test it through public behavior, or move that check into a unit test.
- Tests pass alone but fail together. Test functions run in parallel threads, and integration tests that touch the same file, port, or environment variable collide. Use unique temporary paths, or run with
cargo test -- --test-threads=1to confirm the cause. - Cannot use a test-only crate. The crate is under
[dependencies]in a way you did not intend, or missing from[dev-dependencies]. Test crates need one of the two.
Exercise
A package has only src/main.rs, and a file tests/calc.rs begins with use my_app::compute;. The build fails because the crate cannot be found. What is the minimal change that lets the integration test call compute, and why does it work?
Show answer
Create src/lib.rs, move compute into it (or declare it there) and mark it pub, then have main.rs call it with use my_app::compute;. Integration test crates can only link against a library target. A binary-only package has none. Once lib.rs exists, the test crate links to it and sees its public items.
Exercise
You need a helper function used by tests/a.rs and tests/b.rs. Where do you put it, and how does each file use it?
Show answer
Put it in tests/common/mod.rs as a pub fn. In each test file, add mod common; and call common::helper(). The subdirectory prevents Cargo from compiling the helper as its own test crate, which would happen with tests/common.rs.