Rust Testing: Unit Tests, Integration Tests, and Cargo Doc Tests
Three test kinds with three different visibility rules, plus the commands, attributes and doc-test fences that make cargo test useful.

Quick Summary
Rust has three test kinds built into Cargo, and they differ by what they can see. Unit tests live in the same file as the code inside #[cfg(test)] mod tests, compiled only for cargo test, and can reach private functions. Integration tests live in tests/ and use the crate as an external consumer would — only the public API. Doc tests are the fenced examples in /// comments, compiled and run so documentation cannot rot.
All three run from cargo test, which builds one test binary per integration file plus one for the library's unit tests, and runs them in parallel with output captured unless a test fails. The #[test] attribute marks a function that takes no arguments and returns () or Result<(), E: Debug>; anything else fails to compile.
The design principle worth adopting: test behaviour through the smallest public surface that expresses it, and use #[cfg(test)] only for access to internals that cannot be observed otherwise. A test that reaches into private state is coupled to the implementation it is supposed to protect.
Basic Syntax & Signature
// src/calc.rs
pub fn parse_port(s: &str) -> Result<u16, String> {
let n: u16 = s.trim().parse().map_err(|_| format!("bad port: {s}"))?;
if n == 0 { return Err("port 0 is reserved".into()); }
Ok(n)
}
fn is_private_helper(s: &str) -> bool { s.starts_with("0x") }
// Unit tests: same file, can see private items.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_a_valid_port() {
assert_eq!(parse_port("8080"), Ok(8080));
}
#[test]
fn trims_whitespace() {
assert_eq!(parse_port(" 443 "), Ok(443));
}
#[test]
fn rejects_zero() {
let err = parse_port("0").unwrap_err();
assert!(err.contains("reserved"), "unexpected error: {err}");
}
#[test]
#[should_panic(expected = "attempt to divide by zero")]
fn divides_by_zero() {
let n = 1;
let d = 0;
let _ = n / d;
}
#[test]
fn returns_result_instead_of_panicking() -> Result<(), String> {
// `?` works in a test that returns Result.
let port = parse_port("80")?;
assert_eq!(port, 80);
Ok(())
}
#[test]
#[ignore = "slow: hits the filesystem"]
fn reads_a_real_file() {
assert!(std::fs::metadata("Cargo.toml").is_ok());
}
#[test]
fn private_helpers_are_visible_here() {
assert!(is_private_helper("0xff"));
}
}// tests/public_api.rs — a separate crate that links against your library.
use my_crate::parse_port;
#[test]
fn usable_from_outside() {
assert_eq!(parse_port("3000").unwrap(), 3000);
}
#[test]
fn error_type_is_public() {
assert!(parse_port("nope").is_err());
}// Doc test in src/lib.rs
/// Parses a port number, rejecting zero.
///
/// # Examples
///
/// ```
/// # use my_crate::parse_port;
/// assert_eq!(parse_port("8080")?, 8080);
/// # Ok::<(), String>(())
/// ```
///
/// Invalid input is reported:
///
/// ```should_panic
/// my_crate::parse_port("abc").unwrap();
/// ```
///
/// This one is compiled but not run:
///
/// ```no_run
/// let server = my_crate::start_server("0.0.0.0:8080");
/// ```
pub fn parse_port(s: &str) -> Result<u16, String> {
let n: u16 = s.trim().parse().map_err(|_| format!("bad port: {s}"))?;
if n == 0 { return Err("port 0 is reserved".into()); }
Ok(n)
}Doc test fence attributes: no_run (compile only), ignore (skip entirely), should_panic, compile_fail (must not compile), edition2018 / edition2021, and text (not a test). Lines prefixed with # are hidden from the rendered documentation but included in the compiled test.
Key Comparison Table
| Unit test | Integration test | Doc test | |
|---|---|---|---|
| Location | #[cfg(test)] mod tests in source | tests/*.rs | /// fenced blocks |
| Access | Private and public items | Public API only | Public API only |
| Compiled into | Library test binary | One binary per file | One test per example |
| Speed | Fastest | Link + build per file | Slowest (one rustc run each) |
| Runs with | cargo test --lib | cargo test --test name | cargo test --doc |
| Good for | Logic, edge cases | Public contract | Usage examples that must stay valid |
| Not good for | Cross-crate behaviour | Internals | Long or async-heavy setup |
| Command | Effect |
|---|---|
cargo test | Everything: unit, integration, doc |
cargo test --lib | Unit tests only |
cargo test --test api | One integration file |
cargo test --doc | Doc tests only |
cargo test name_fragment | Tests whose path contains the fragment |
cargo test -- --nocapture | Show stdout from passing tests |
cargo test -- --test-threads=1 | Serial execution |
cargo test -- --ignored | Run only ignored tests |
cargo test --release | Optimized build, catches overflow-wrapping differences |
Practical Edge Cases & Deep Dives
1. Shared helpers in integration tests without a false test binary
// tests/common/mod.rs — a module, not a test file, so it is not run alone.
pub fn fixture_path(name: &str) -> std::path::PathBuf {
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name)
}
// tests/parsing.rs
mod common;
#[test]
fn reads_fixture_file() {
let p = common::fixture_path("sample.txt");
assert!(p.to_string_lossy().ends_with("sample.txt"));
}Putting the helper in tests/common.rs instead of tests/common/mod.rs makes Cargo treat it as its own integration test binary, which compiles and reports a common test target with zero tests. The mod.rs form is the documented workaround.
2. Testing error paths and panics correctly
#[cfg(test)]
mod tests {
#[test]
#[should_panic(expected = "index out of bounds")]
fn panic_message_is_asserted() {
let v: Vec<u8> = vec![];
let _ = v[0];
}
#[test]
fn panics_can_be_inspected() {
let result = std::panic::catch_unwind(|| {
let v: Vec<u8> = vec![];
v[0]
});
assert!(result.is_err());
}
#[test]
fn errors_can_be_matched() {
let err = std::str::from_utf8(&[0xff]).unwrap_err();
assert_eq!(err.valid_up_to(), 0);
}
}#[should_panic] without expected passes on any panic, including an accidental one from a bug in setup, which makes it a weak assertion. Always supply expected with a substring of the real message. Note that should_panic cannot be combined with a Result return type, and it only observes panics on the test's own thread — a panic inside a spawned thread does not satisfy it.
3. Async tests and the missing runtime
// Cargo.toml: tokio = { version = "1", features = ["rt", "macros", "time"] }
#[tokio::test]
async fn async_work_completes() {
let v = tokio::spawn(async { 1 + 1 }).await.unwrap();
assert_eq!(v, 2);
}
// Time-dependent code: pause the clock instead of sleeping.
#[tokio::test(start_paused = true)]
async fn timeout_fires() {
let start = std::time::Instant::now();
let r = tokio::time::timeout(
std::time::Duration::from_secs(5),
tokio::time::sleep(std::time::Duration::from_secs(30)),
)
.await;
assert!(r.is_err());
assert!(start.elapsed() < std::time::Duration::from_secs(1));
}A plain #[test] on an async fn does not compile ("async fn is not supported by the test attribute"). #[tokio::test] builds a single-threaded runtime per test; start_paused makes the test instant regardless of the sleep duration, which is the difference between a fast suite and one that takes minutes.
4. Doc tests that stay honest
/// Computes the checksum used by the wire protocol.
///
/// ```
/// # use my_crate::checksum;
/// ```
/// A wrong-length input is rejected:
///
/// ```compile_fail
/// # use my_crate::checksum;
/// let bad = checksum(&[1, 2, 3]); // requires exactly 4 bytes
/// ```
pub fn checksum(bytes: &[u8; 4]) -> u8 {
bytes.iter().fold(0u8, |acc, b| acc.wrapping_add(*b))
}compile_fail is the only way to assert that an API rejects misuse at compile time — for example that a type has no Clone, or that a function refuses an unsized argument. The test passes if the snippet fails to compile for any reason, so pair it with a comment and keep the snippet tiny. Doc tests run against the public API of a library crate; a binary crate's doc tests are not run by default.
5. Deterministic tests: time, randomness, environment
#[cfg(test)]
mod tests {
fn is_expired(now: u64, issued: u64, ttl: u64) -> bool {
now.saturating_sub(issued) > ttl
}
#[test]
fn expiry_boundary_is_inclusive_at_ttl() {
// Pass time in; never call SystemTime::now() inside the logic.
assert!(!is_expired(1_000, 1_000, 10));
assert!(!is_expired(1_010, 1_000, 10));
assert!(is_expired(1_011, 1_000, 10));
}
#[test]
fn env_is_read_only_when_needed() {
// Tests run in parallel in one process, so mutating the environment
// races. In edition 2024, `set_var` is unsafe for this reason.
let value = std::env::var("MY_TEST_FLAG").unwrap_or_default();
assert!(value.is_empty() || value == "1");
}
}The pattern that removes nearly all flakiness: pass now, random seeds, and configuration in as parameters. When that is impossible, serial_test's #[serial] or a tempfile::TempDir per test keeps parallel tests from colliding over shared paths.
6. Integration test with a real HTTP handler
// tests/server.rs
use std::io::{Read, Write};
use std::net::TcpListener;
fn spawn_server() -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for stream in listener.incoming().take(1) {
let mut s = stream.unwrap();
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf);
s.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok").unwrap();
}
});
port
}
#[test]
fn handler_responds_ok() {
let port = spawn_server();
let resp = std::process::Command::new("curl")
.args(["-s", "-o", "/dev/null", "-w", "%{http_code}", &format!("http://127.0.0.1:{port}/")])
.output()
.unwrap();
assert_eq!(String::from_utf8_lossy(&resp.stdout), "200");
}Binding port 0 and reading back local_addr() avoids port collisions between parallel test processes, which is the usual cause of "address already in use" in CI. The spawned thread is detached; the test process exits after the assertion, so no join is required for a one-shot check like this.
Common Compilation/Runtime Mistakes
| Error / symptom | Cause | Fix |
|---|---|---|
can't find crate for 'my_crate' in tests/ | Integration test cannot import a binary crate | Move logic into src/lib.rs |
async fn not supported by #[test] | Missing runtime attribute | #[tokio::test] or #[async_std::test] |
assert_eq! requires Debug | Type under comparison lacks Debug | Derive Debug, or use assert!(a == b) |
| Test passes locally, fails in CI | Parallel tests sharing a file, port, or env var | Unique temp paths, port 0, #[serial] |
#[should_panic] passes for the wrong reason | Any panic satisfies it | Add expected = "..." |
| Doc test compiles but the example is wrong | Hidden # lines mask setup | Keep hidden lines minimal, assert outcomes |
cargo test runs nothing | Tests not marked #[test], or module not mod-declared | Add #[test] and mod tests; |
unused import: super::* | #[cfg(test)] module not compiled outside tests | Expected; gate with #[cfg(test)] |
| Long suite, mostly one test | Unpaused sleeps or real network calls | start_paused, fakes, --test-threads |
0 tests target named after a helper file | tests/helpers.rs treated as a test file | Move to tests/helpers/mod.rs |
One last habit: run cargo test --all-targets before pushing. cargo test alone skips examples and benches, and an example that no longer compiles is a broken published crate even when every test is green.
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.