How can I create parameterized tests in Rust?

后端 未结 6 2081
生来不讨喜
生来不讨喜 2021-02-05 01:20

I want to write test cases that depend on parameters. My test case should be executed for each parameter and I want to see whether it succeeds or fails for each parameter.

6条回答
  •  再見小時候
    2021-02-05 01:32

    My rstest crate mimics pytest syntax and provides a lot of flexibility. A Fibonacci example can be very neat:

    #[cfg(test)]
    mod test {
        use super::*;
    
        use rstest::rstest;
    
        #[rstest(input, expected,
        case(0, 0),
        case(1, 1),
        case(2, 1),
        case(3, 2),
        case(4, 3),
        case(5, 5),
        case(6, 8)
        )]
        fn fibonacci_test(input: u32, expected: u32) {
            assert_eq!(expected, fibonacci(input))
        }
    }
    
    pub fn fibonacci(input: u32) -> u32 {
        match input {
            0 => 0,
            1 => 1,
            n => fibonacci(n - 2) + fibonacci(n - 1)
        }
    }
    

    Output:

    /home/michele/.cargo/bin/cargo test
       Compiling fib_test v0.1.0 (file:///home/michele/learning/rust/fib_test)
        Finished dev [unoptimized + debuginfo] target(s) in 0.92s
         Running target/debug/deps/fib_test-56ca7b46190fda35
    
    running 7 tests
    test test::fibonacci_test::case_1 ... ok
    test test::fibonacci_test::case_2 ... ok
    test test::fibonacci_test::case_3 ... ok
    test test::fibonacci_test::case_5 ... ok
    test test::fibonacci_test_case_6 ... ok
    test test::fibonacci_test::case_4 ... ok
    test test::fibonacci_test::case_7 ... ok
    
    test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
    

    Every case is run as a single test case.

    The syntax is simple and neat and, if you need, you can use any Rust expression as the value in the case argument.

    rstest also supports generics and pytest-like fixtures.


    Don't forget to add rstest to dev-dependencies in Cargo.toml.

提交回复
热议问题