Cargo and Testing
Build, test, and manage dependencies with Cargo. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Search across all documentation pages
Build, test, and manage dependencies with Cargo. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Run unit and integration tests.
// cargo test
// cargo test my_test_name
// cargo test -- --nocaptureMark unit tests next to code under cfg(test).
#[cfg(test)]
mod tests {
#[test]
fn adds() {
assert_eq!(1 + 1, 2); // passes
}
}Pretty assertion with Debug on mismatch.
assert_eq!(2 + 2, 4);
assert_ne!(1, 2);Expect a panic in a test.
#[test]
#[should_panic(expected = "boom")]
fn panics() {
panic!("boom");
}Tests may return Result for ?.
#[test]
fn parses() -> Result<(), std::num::ParseIntError> {
let n: i32 = "3".parse()?;
assert_eq!(n, 3);
Ok(())
}Add dependencies from the CLI.
// cargo add serde --features derive
// cargo add tokio --features fullOptimized builds for production.
// cargo build --release
// target/release/<bin>Lint and format.
// cargo fmt
// cargo clippy -- -D warningstests/ directory compiles as separate crates.
// tests/api.rs
// use mycrate::foo;Examples in /// docs are tested.
/// Adds one.
/// ```
/// assert_eq!(1 + 1, 2);
/// ```
pub fn demo() {}Skip expensive tests by default.
#[test]
#[ignore]
fn slow() { /* cargo test -- --ignored */ }Inspect dependency graph.
// cargo tree -i serdeEnable features when testing.
// cargo test --features fullMicrobenchmarks via criterion or libtest-bench.
// #[bench] unstable; prefer criterion crateSingle-file experiments with cargo script / rust-script tools.
// rustc --edition 2024 main.rs && ./mainStack versions: Rust 1.97.0 · edition 2024 · Tokio 1.x · serde 1.0
Reviewed by Chris St. John·Last updated Jul 18, 2026