Unit Testing
Filtering Tests
Filtering tests runs a specific subset of a test suite by matching test names and module paths against substring filters, exact matches (--exact), or exclusion patterns (--skip).
Full Test Name in Harness: `storage::cache::tests::evicts_expired_keys`
|<--- module path --->|<--- fn name ----->|
Matched by substring filter:
- `cargo test evicts`
- `cargo test storage::cache`
- `cargo test cache::tests::evicts`
Substring Matching by Function Name or Module Path
When you pass a filter string to cargo test <FILTER>, the test harness compares <FILTER> against each test's fully qualified module path and function name (relative to the crate root). Any test whose full path contains <FILTER> as a substring is executed, and all other tests are reported as filtered out.
pub mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn mul(a: i32, b: i32) -> i32 {
a * b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn add_two_numbers() {
assert_eq!(add(2, 3), 5);
}
#[test]
fn add_negative_numbers() {
assert_eq!(add(-4, -6), -10);
}
#[test]
fn mul_two_numbers() {
assert_eq!(mul(3, 4), 12);
}
}
}
fn main() {
println!("2 + 3 = {}, 3 * 4 = {}", math::add(2, 3), math::mul(3, 4));
}
2 + 3 = 5, 3 * 4 = 12
Running cargo test add executes only the two tests containing "add" and filters out mul_two_numbers:
running 2 tests
test math::tests::add_negative_numbers ... ok
test math::tests::add_two_numbers ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s
Exact Matching, Multiple Filters, and --skip
| Command | Effect |
|---|---|
cargo test add |
Runs all tests whose module path or name contains "add". |
cargo test math::tests::add_two_numbers -- --exact |
Runs only the test whose full path exactly equals math::tests::add_two_numbers. |
cargo test -- --skip negative |
Runs all tests except those containing "negative". |
cargo test add -- --skip negative |
Runs tests containing "add" while excluding any that also contain "negative". |
cargo test -- add mul |
Runs tests matching either "add" or "mul" (multiple filters passed after --). |
cargo test -- --list |
Lists all test and benchmark names in the suite without running them. |
# List all matching tests without executing them
cargo test add -- --list
math::tests::add_negative_numbers: test
math::tests::add_two_numbers: test
2 tests, 0 benchmarks