Sub topic 11
Fewer test binaries, faster test builds
This chapter assumes you can write Rust unit and integration tests and run cargo test. It also assumes you know what a workspace is and have read the chapters on linking and workspaces. Here you will learn why the layout of your tests affects build time, how to merge integration tests into one binary, and which trade-offs come with that.
Why test layout matters for build time
Every file directly under tests/ is its own crate. Cargo compiles it separately, links it into its own executable, and runs it separately. A project with 20 files in tests/ therefore produces 20 test executables, plus one for the unit tests inside src/, plus one per doctest.
Each of these executables pays for several things:
- Compiling the test crate, which re-reads the library's public API metadata.
- Instantiating generic code from your library again, because monomorphized copies are not shared across crates.
- Linking a full binary. Test binaries link the test harness and your library and its dependencies, and debug builds carry a lot of debug info.
The link step is often the biggest cost, and it repeats once per binary. A small test file that takes 0.2 seconds to compile can take several seconds to link, and the same libraries get linked again for each file.
See how many test binaries you have
Cargo prints one Running line per executable. List them without running the tests:
cargo test --no-runLook for lines like Executable tests/auth.rs (target/debug/deps/auth-1a2b3c4d). Each line is one link step.
To see where the time goes, use the timings report from the measuring chapter:
cargo test --no-run --timingsIn the report, each test target appears as its own bar. If many short bars each end with a long link segment, merging tests will help. If one large test crate dominates, merging will not.
Merge integration tests into one binary
The usual fix is to keep a single integration test crate and make the other files modules of it. Cargo treats a file tests/name.rs as a crate root, but it does not treat files in subdirectories as crates. So you move the test files into a subdirectory and add one entry point.
Before:
tests/
auth.rs
billing.rs
search.rsAfter:
tests/
integration/
main.rs
auth.rs
billing.rs
search.rsCargo finds tests/integration/main.rs and builds one test target named integration. The main.rs file declares the modules:
// tests/integration/main.rs
mod auth;
mod billing;
mod search;Each module file contains ordinary tests. Here is a complete example for one of them:
// tests/integration/auth.rs
#[test]
fn rejects_empty_password() {
assert!(!is_valid_password(""));
}
#[test]
fn accepts_long_password() {
assert!(is_valid_password("correct horse battery staple"));
}
fn is_valid_password(p: &str) -> bool {
p.len() >= 8
}In a real project, these tests would call your library with use my_crate::...;. The helper above is local only so that the example runs on its own.
After the move, cargo test --no-run lists one integration executable instead of three. You can still run a subset by name:
cargo test --test integration auth::The --test integration flag selects the target, and auth:: filters by module path.
Shared helpers come for free
Before merging, a common pattern was tests/common/mod.rs, which every test file included with mod common;. That compiled the helper code once per test crate. In a merged crate, declare it once:
// tests/integration/main.rs
mod common;
mod auth;
mod billing;Put the helper in tests/integration/common.rs or tests/integration/common/mod.rs. Every module reaches it with crate::common::....
Trade-offs of merging
Merging is not free. Know these effects before you do it.
| Effect | Separate binaries | One merged binary |
|---|---|---|
| Link steps | One per file | One |
| Process isolation | Each file runs in its own process | All tests share one process |
| Global state | Cannot leak between files | Statics and environment variables are shared |
| Rebuild after editing one test | Only that crate | The whole merged crate |
| Parallelism at build time | Many crates build at once | One crate, compiled mostly sequentially |
| Failure impact | A crash stops one file's run | A crash or `process::exit` stops all tests in the binary |
Two cases deserve attention.
First, tests that rely on process-wide state. A test that sets an environment variable, changes the current directory, or initializes a global logger can now affect tests from other files. Rust already runs tests in a binary on several threads, so such tests were fragile inside a file. Merging widens the problem to every file. Fix this by avoiding global state, or by serializing those tests with a lock or a crate such as serial_test.
Second, tests that need their own main. A test target with harness = false provides its own entry point, for example a custom runner. Such a target cannot be merged into the standard harness crate. Keep it separate.
Move tests that do not need the public API
Integration tests can only use the public API of your crate, so they re-link against the finished library. Unit tests in #[cfg(test)] modules inside src/ live in the same crate as the code under test. They compile into the single unit-test binary, which is built once for the whole library.
If a test only checks internal logic, moving it into a #[cfg(test)] mod tests block removes one binary from the build:
// src/lib.rs
pub fn add(a: u32, b: u32) -> u32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_numbers() {
assert_eq!(add(2, 3), 5);
}
}Keep true integration tests, the ones that exercise the library as an outside user would, in tests/.
Doctests are separate executables too
Each documentation example is compiled as its own tiny program and linked on its own. A crate with hundreds of doctests can spend more time on them than on all other tests combined. Rustdoc batches doctests in some editions, but each still costs a compile and often a link.
Options to reduce the cost:
- Mark examples that only illustrate syntax with
no_run(compiled but not executed) orignore(not compiled). Useignoresparingly because ignored code can rot. - Keep doctests short and focused on the public API. Move longer scenarios into regular tests.
- During the inner loop, skip them with
cargo test --lib --tests, and run the fullcargo testbefore you push.
Choose targets when you run tests
You do not always need every target. These forms build only what you ask for:
# Unit tests in the library only
cargo test --lib
# One integration target
cargo test --test integration
# All unit and integration tests, no doctests
cargo test --lib --tests
# A single package in a workspace
cargo test -p coreIn a workspace, running cargo test at the root builds the tests for every member. Use -p during development so you only link what you are working on.
Control the debug info in test builds
Test binaries are built with the test profile, which inherits from dev. The debug setting you chose in the profile chapter therefore applies. Setting debug = "line-tables-only" shrinks every test binary and speeds up each link. Because the link is repeated per binary, this saving multiplies with the number of binaries you have.
# Cargo.toml
[profile.dev]
debug = "line-tables-only"If you use a faster linker, the same multiplication works in your favor: a link that takes 1 second instead of 4 saves three seconds on each binary.
Declare targets explicitly when needed
Cargo discovers test targets automatically from the tests/ directory. If you want to name targets yourself, or turn off discovery so that a stray file does not become a new binary, set autotests = false and list the targets:
# Cargo.toml
[package]
name = "my_crate"
version = "0.1.0"
edition = "2021"
autotests = false
[[test]]
name = "integration"
path = "tests/integration/main.rs"With autotests = false, a new file dropped at tests/foo.rs is ignored by Cargo. This keeps the binary count from creeping back up as the project grows. The cost is that you must register any additional target by hand.
A workflow for deciding
Always re-measure after the change. If the total time did not drop, revert and look elsewhere.
Common errors
- Tests silently disappear. A file in
tests/integration/that is not declared withmod name;inmain.rsis not compiled, so its tests never run. Compare the test count before and after the merge. - "unused" warnings appear. Helper functions used by only some modules were previously flagged once per crate. In a merged crate, warnings change. Fix them with real usage or a targeted
#[allow(dead_code)]on the helper. - Name clashes. Two files that both defined a top-level function
setupnow live in different modules, so they do not clash. But twomod common;declarations at the crate root do. Declare each module once. - Flaky tests after merging. Check for shared environment variables, files, ports, or global state. These are the usual cause.
Exercise
A project has 12 files in tests/, and cargo test --no-run --timings shows that each test target spends most of its time linking. You merge them into tests/integration/main.rs. Name one benefit and two risks of this change. Then name one kind of test target you must leave out of the merge.
Show answer
Benefit: the 12 link steps become one, so a clean test build is faster. Risks: tests now share one process, so global state such as environment variables or a logger can leak between former files; and editing any one test file recompiles the whole merged crate, which can slow the edit loop. (A crash or process::exit in one test also ends the whole run.) Leave out any target that sets harness = false and supplies its own main, because it cannot be a module of the standard test harness crate.
Exercise
You add a new file tests/integration/refunds.rs with two tests, but cargo test reports the same number of tests as before. What is the most likely cause, and how do you fix it?
Show answer
The file is not declared as a module. Add mod refunds; to tests/integration/main.rs. Files in a subdirectory of tests/ are not crate roots, so Cargo only compiles them if the entry point declares them.