参数化测试用于当需要使用多组不同的测试数据测试同一个方法的时候。
使用参数化测试的要点:
① 为该测试方法专门生成一个新的类;
② 指定类的Runner为org.junit.runners.Parameterized类;
③ 声明几个变量,用于存放测试数据和预期结果;
④ 定义一个用于准备数据的公共静态方法,该方法使用org.junit.runners.Parameterized.Parameters标注进行修饰,在方法中定义一个java.util.Collection存放测试数据和预期结果,并将该Collection作为返回值;
⑤ 创建一个带参的构造函数,并在其中对③中的变量赋值;
⑥ 编写测试方法,使用③中的变量进行测试。
参数化测试的执行流程:prepareData() → MaxTest(arg1, arg2, expected) → testMax()
import static org.junit.Assert.*;
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 MaxTest {
private double arg1 = 0;
private double arg2 = 0;
private double expected = 0;
public MaxTest(double arg1, double arg2, double expected) {
this.arg1 = arg1;
this.arg2 = arg2;
this.expected = expected;
}
@Parameters
public static Collection<Object[]> prepareData() {
Object[][] objects = {{1, 2, 2}, {2, 1, 2}, {1, 1, 1}};
return Arrays.asList(objects);
}
@Test
public void testMax() {
double result = Math.max(arg1, arg2);
assertEquals(expected, result, 0);
}
}