DEV Community

Cover image for [Rust Guide] 11.7. Running Tests by Name
SomeB1oody
SomeB1oody

Posted on

[Rust Guide] 11.7. Running Tests by Name

If you find this helpful, please like, bookmark, and follow. To keep learning along, follow this series.

11.7.1 Running a Subset of Tests by Name

If you want to choose which tests to run, pass the test name or names as arguments to cargo test.

For example:

pub fn add_two(a: usize) -> usize {
    a + 2
}

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

    #[test]
    fn add_two_and_two() {
        let result = add_two(2);
        assert_eq!(result, 4);
    }

    #[test]
    fn add_three_and_two() {
        let result = add_two(3);
        assert_eq!(result, 5);
    }

    #[test]
    fn one_hundred() {
        let result = add_two(100);
        assert_eq!(result, 102);
    }
}
Enter fullscreen mode Exit fullscreen mode

If you only want to run the one_hundred test, write cargo test one_hundred:

$ cargo test one_hundred
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished `test` profile [unoptimized +debuginfo] target(s) in 0.69s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 1 test
test tests::one_hundred ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.00s
Enter fullscreen mode Exit fullscreen mode

To run a single test, just specify its exact name. To run multiple tests, specify part of the test name (module names work too) as the argument, and all tests that match that name will run.

For example, if I want to run add_two_and_two() and add_three_and_two, both of which contain add in their names, I can write cargo test add:

$ cargo test add
   Compiling adder v0.1.0 (file:///projects/adder)
    Finished `test` profile [unoptimized +debuginfo] target(s) in 0.61s
     Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)

running 2 tests
test tests::add_three_and_two ... ok
test tests::add_two_and_two ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s
Enter fullscreen mode Exit fullscreen mode

Top comments (0)