Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

11.7 按测试的名称运行测试

11.7.1. 按名称运行测试的子集

如果想选择运行哪些测试,就把测试名称(一个或多个)作为参数传给cargo test

看个例子:

#![allow(unused)]
fn main() {
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);
    }
}
}

如果只想运行one_hundred这个测试,就写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.12s
     Running unittests src/lib.rs (target/debug/deps/adder-302521ba8d0f0bdf)

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

运行单个测试时,直接指定它的精确名称即可。运行多个测试时,指定测试名的一部分(模块名也可以)作为参数,所有匹配该名称的测试都会运行。

举个例子,假如我想运行add_two_and_two()add_three_and_two,这两个测试的名称都含有add,就可以写cargo test add

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

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