cargo test: Rust's All-in-One Test Runner
`cargo test` is Rust's built-in test runner, automatically discovering and executing unit, integration, and documentation tests. Use it to validate code marked with `#[test]` and examples in docs.
WHY IT EXISTS: To provide a single, standardized command for running all types of tests in a Rust project. Without it, developers would need separate tools and manual steps to run unit tests, integration tests, and documentation examples, leading to inconsistency and friction in the development cycle.
THE MENTAL MODEL: Think of cargo test as a test coordinator, not just a runner. It first compiles your code into special test executables. Each executable is linked with Rust's libtest framework, which then discovers and runs functions marked with the #[test] attribute, often in parallel.
HOW IT WORKS: When you run the command, Cargo invokes the Rust compiler (rustc) with a --test flag. This builds a test binary that includes the libtest harness. This harness automatically finds and executes all functions annotated with #[test]. Separately, cargo test also runs documentation tests by using rustdoc to extract, compile, and run the code examples found in your documentation comments. By default, unit, integration, and doc tests are all run. For consistency, the working directory for each test is set to the root of the package it belongs to.
WHEN TO USE IT: Use cargo test continuously during development to verify your code's correctness. Run it in CI/CD pipelines to automate quality checks. You can filter which tests to run by passing a name. For larger projects, you can target specific packages within a workspace using flags like --package or test the entire workspace with --workspace.
WHEN NOT TO USE IT: cargo test is not designed for manual, exploratory testing. It is also not a full-fledged end-to-end testing framework that manages complex external environments, although it can be a component of one. If you need full control and want to bypass Rust's default test harness, you can set harness = false in your Cargo.toml and write your own main function to manage test execution.
ONE CANONICAL EXAMPLE: To run only tests whose names contain "foo" and execute them across 3 parallel threads, you must separate Cargo's arguments from the test binary's arguments using --. The command is: cargo test foo -- --test-threads 3. Here, foo is a filter for the test binary, and --test-threads 3 is an option for that same binary.
Read the original → doc.rust-lang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.