`cargo test`
cargo test compiles your crate in test mode and runs unit tests, integration tests, and doc tests. Filters, -- --nocapture, and --test-threads control what runs and what you see.
Detailed Explanation
cargo test is the one command. It builds the library or binary with cfg(test), links the test harness, and runs every #[test], then the tests/ crates, then rustdoc tests. A failure in any of those is a non-zero exit. CI should run cargo test (and usually cargo test --all-features if features interact).
Arguments before -- are for Cargo: cargo test --release, cargo test --test integration, cargo test -p the_crate. Arguments after -- are for the harness: cargo test -- parse_port filters by substring, cargo test -- --nocapture prints println! from tests, cargo test -- --test-threads=1 serialises. --ignored runs #[ignore] tests.
The default parallelism is one thread per test, as many as CPUs. Tests that share a port, a file path, or a process-wide env::set_var will flake. Fix the isolation or serialise that file. Do not start with --test-threads=1 for the whole suite unless you must; it hides races and slows CI.
cargo test uses the dev profile by default, so overflow checks are on and optimisations are off. That is what you want for correctness. cargo test --release is for tests that are otherwise too slow, and it can hide overflow panics. Know which one CI runs.
When you run cargo test: every change. When you filter: a tight loop on one test. When you add --nocapture: you are debugging a print. When you add --ignored: a slow or network test you opted out of the default suite.
Workspaces run cargo test --workspace in CI so a crate you did not touch still builds its tests. --all-features and --no-default-features catch feature-flag combinations that a local default build misses. A feature that does not compile is a broken crate even if nobody enabled it on your laptop today.
Code Examples
fn mul(a: i32, b: i32) -> i32 {
a * b
}
#[test]
fn multiplies() {
assert_eq!(mul(6, 7), 42);
}Common Gotchas
Harness flags go after `--`
`cargo test --nocapture` is a Cargo error. `cargo test -- --nocapture` prints stdout.
Parallel tests plus global state flake
Temp files, env vars, and bound ports need unique names or a lock.
`--release` changes overflow behaviour
A test that relies on a debug overflow panic will pass in release. Prefer explicit `checked_*`.
`cargo test parse` filters by name
It runs every test whose path contains `parse`. Use a more specific string when the suite is large.