How can I create parameterized tests in Rust?

后端 未结 6 2074
生来不讨喜
生来不讨喜 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

    The built-in test framework does not support this; the most common approach used is to generate a test for each case using macros, like this:

    macro_rules! fib_tests {
        ($($name:ident: $value:expr,)*) => {
        $(
            #[test]
            fn $name() {
                let (input, expected) = $value;
                assert_eq!(expected, fib(input));
            }
        )*
        }
    }
    
    fib_tests! {
        fib_0: (0, 0),
        fib_1: (1, 1),
        fib_2: (2, 1),
        fib_3: (3, 2),
        fib_4: (4, 3),
        fib_5: (5, 5),
        fib_6: (6, 8),
    }
    

    This produces individual tests with names fib_0, fib_1, &c.

提交回复
热议问题