24.4 The cargo test Command

Command-Line Convention
In cargo test myfile -- --test-threads=1, the first -- ends Cargo-specific options, and arguments after it (e.g., --test-threads=1) are passed to the Rust test framework.
Running cargo test --help displays Cargo-specific options, while cargo test -- --help displays options for the Rust test framework.

By default, cargo test compiles your tests and runs all recognized test functions:

cargo test

The output shows which tests pass and which fail.

24.4.1 Running a Single Named Test

You can run only the tests whose names match a particular pattern:

cargo test failing

This executes any tests whose names contain the substring "failing".

24.4.2 Running Tests in Parallel

The Rust test harness runs tests in parallel (using multiple threads) by default. To disable parallel execution:

cargo test -- --test-threads=1

24.4.3 Showing or Hiding Output

By default, standard output is captured and shown only if a test fails. To see all output:

cargo test -- --nocapture

24.4.4 Filtering by Name Pattern

As mentioned, cargo test some_pattern runs only those tests whose names contain some_pattern. This is useful for targeting specific tests.

24.4.5 Ignoring Tests

Some tests may be long-running or require a special environment. Mark them with #[ignore]:

#[test]
#[ignore]
fn slow_test() {
    // ...
}

Ignored tests do not run unless you explicitly request them:

cargo test -- --ignored

24.4.6 Using Result<T, E> in Tests

Instead of panicking, you can make a test return Result<(), String>:

#[test]
fn test_with_result() -> Result<(), String> {
    if 2 + 2 == 4 {
        Ok(())
    } else {
        Err("Math is broken".into())
    }
}

If the test returns Err(...), it fails with that message.

Tests and ?

Having your tests return Result<T, E> lets you use the ? operator for error handling:

fn sqrt(number: f64) -> Result<f64, String> {
    if number >= 0.0 {
        Ok(number.powf(0.5))
    } else {
        Err("negative floats don't have square roots".to_owned())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sqrt() -> Result<(), String> {
        let x = 4.0;
        assert_eq!(sqrt(x)?.powf(2.0), x);
        Ok(())
    }
}

You cannot use the #[should_panic] attribute on tests that return Result<T, E>. If you need to ensure a function returns Err(...), don’t apply the ? operator on the result. Instead, use something like assert!(value.is_err()).