24.4 Controlling Test Execution

Cargo offers several options to control which tests run and how they execute.

24.4.1 Running Specific Tests

  • Filter by Name: Run only tests whose names contain a specific substring. The filter applies to the test function’s full path (e.g., module::test_name).
    # Runs tests with "api" in their name, like test_public_api_call
    cargo test api
    
    # Runs only the test named test_internal_logic within the tests module
    cargo test tests::test_internal_logic
    
  • Run Specific Integration Test File: Execute all tests within a particular file in the tests/ directory.
    # Runs all #[test] functions in tests/api_usage.rs
    cargo test --test api_usage
    
  • Run Only Library Unit Tests:
    cargo test --lib
    
  • Run Only Documentation Tests:
    cargo test --doc
    

24.4.2 Ignoring Tests

Tests that are slow, require specific environments (e.g., network access), or are currently flaky can be marked with the #[ignore] attribute.

#[test]
fn very_fast_test() { /* ... */ }

#[test]
#[ignore = "Requires network access and is slow"] // Optional reason string
fn test_external_service() {
    // ... code that might take a long time or fail intermittently ...
}
  • Ignored tests are skipped by default when running cargo test.
  • To run only the ignored tests:
    cargo test -- --ignored
    
  • To run all tests, including those marked as ignored:
    cargo test -- --include-ignored
    

Note on --: Arguments placed after a standalone -- are passed directly to the test runner executable built by Cargo, not to Cargo itself. Use cargo test -- --help to see options accepted by the test runner, such as --ignored, --include-ignored, --test-threads, and --nocapture. Contrast this with cargo test --help, which shows Cargo’s own command-line options.

24.4.3 Controlling Parallelism and Output

  • Parallel Execution: By default, cargo test runs tests in parallel using multiple threads for faster execution. If tests might interfere with each other (e.g., accessing the same file or resource without synchronization) or if sequential execution simplifies debugging, parallelism can be disabled:
    # Run tests sequentially using only one thread
    cargo test -- --test-threads=1
    
  • Capturing Output: Standard output (println!) and standard error (eprintln!) generated by passing tests are captured by default and not displayed. Output from failing tests is shown. To display the output from all tests, regardless of their status:
    # Show all stdout/stderr from all tests
    cargo test -- --nocapture