单元测试~JUnit4 参数化测试

参数化测试

官方demo

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class FibonacciTest {

    private int fInput;

    private int fExpected;

    public FibonacciTest(int input, int expected) {
        fInput= input;
        fExpected= expected;
    }

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {     
            { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }  
        });
    }

    @Test
    public void test() {
        assertEquals(fExpected, Fibonacci.compute(fInput));
    }
}
public class Fibonacci {
    public static int compute(int n) {
        int result = 0;

        if (n <= 1) { 
            result = n; 
        } else { 
            result = compute(n - 1) + compute(n - 2); 
        }

        return result;
    }
}

在测试类上添加@RunWith(Parameterized.class)注解,通过参数值Parameterized.class指定测试的运行环境

必须提供一个public修饰的带参的构造函数
若无带参的public修饰的构造函数,则单元测试无法执行
这里写图片描述

@Parameters注解标记在创建测试数据的方法上,该方法必须是被public static修饰
这里写图片描述

利用在字段上使用@Parameter注解来取代构造函数
修改代码如下

//    private int fInput;
//
//    private int fExpected;
//
//     FibonacciTest(int input, int expected) {
//        fInput= input;
//        fExpected= expected;
//    }

    @Parameter // first data value (0) is default
    public /* NOT private */ int fInput;

    @Parameter(1)
    public /* NOT private */ int fExpected;

猜你喜欢

转载自blog.csdn.net/quan20111992/article/details/80174908