How can I create parameterized tests in Rust?

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

    Probably not quite what you've asked for, but by using TestResult::discard with quickcheck you can test a function with a subset of a randomly generated input.

    extern crate quickcheck;
    
    use quickcheck::{TestResult, quickcheck};
    
    fn fib(n: u32) -> u32 {
        match n {
            0 => 0,
            1 => 1,
            _ => fib(n - 1) + fib(n - 2),
        }
    }
    
    fn main() {
        fn prop(n: u32) -> TestResult {
            if n > 6 {
                TestResult::discard()
            } else {
                let x = fib(n);
                let y = fib(n + 1);
                let z = fib(n + 2);
                let ow_is_ow = n != 0 || x == 0;
                let one_is_one = n != 1 || x == 1;
                TestResult::from_bool(x + y == z && ow_is_ow && one_is_one)
            }
        }
        quickcheck(prop as fn(u32) -> TestResult);
    }
    

    I took the Fibonacci test from this Quickcheck tutorial.


    P.S. And of course, even without macros and quickcheck you still can include the parameters in the test. "Keep it simple".

    #[test]
    fn test_fib() {
        for &(x, y) in [(0, 0), (1, 1), (2, 1), (3, 2), (4, 3), (5, 5), (6, 8)].iter() {
            assert_eq!(fib(x), y);
        }
    }
    

提交回复
热议问题