当前位置: 代码迷 >> 综合 >> 单元测试~JUnit4 参数化测试
  详细解决方案

单元测试~JUnit4 参数化测试

热度:76   发布时间:2023-12-08 17:33:54.0

参数化测试

官方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;}@Parameterspublic static Collection<Object[]> data() {return Arrays.asList(new Object[][] {     { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }  });}@Testpublic 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 defaultpublic /* NOT private */ int fInput;@Parameter(1)public /* NOT private */ int fExpected;
  相关解决方案