携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第15天,点击查看活动详情
在进行测试的过程中,除了我们通过编写测试用例进行测试之外,还存在一种测试情况,就是需要通过数据进行参数化测试。也就是数据驱动测试。这也是我们在单元测试过程中的基本需求场景。Parameterized就是用于测试用例参数化测试的Runner,那么Parameterized应该如何使用呢?下面进行介绍。
待测试的场景,有如下方法需要测试:
public class Calculator {
public int add(int i,int j){
return i+j;
}
}
复制代码
采用Parameterized进行测试:
@RunWith(Parameterized.class)
public class ParameterizedTest {
@Parameters
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][]{{0, 0, 0}, {2, 1, 1}, {3, 2, 1},
{5, 3, 2}, {7, 4, 3}, {10, 5, 5}, {14, 6, 8}});
}
@Parameter(0)
public int expected;
@Parameter(1)
public int p1;
@Parameter(2)
public int p2;
@Test
public void testAdd() {
Calculator calculator = new Calculator();
System.out.println("Addition with parameters : " + p1 + " and "
+ p2);
assertEquals(expected, calculator.add(p1, p2), 0);
}
}
复制代码
@Parameters定义了一个方法,这个方法返回一个list。list有三个项,这些项定义在 @Parameter(0)上, @Parameter标签的顺序标识了这些项的顺序。
@Parameter(0)
public int expected;
@Parameter(1)
public int p1;
@Parameter(2)
public int p2;
复制代码
上述标识为,expected为二维数组第一项的第一列,p1为第二列,p3为第三列。 上述代码执行结果:
需要注意的是,采用Parameter标注参数的位置的时候,参数只能通过public修饰。 当然,还有另外一种办法来进行参数化,这周办法可以将参数改为private的方式。如下:
@RunWith(Parameterized.class)
public class ParameterizedTest1 {
@Parameters
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][]{{0, 0, 0}, {2, 1, 1}, {3, 2, 1},
{5, 3, 2}, {7, 4, 3}, {10, 5, 5}, {14, 6, 8}});
}
private int expected;
private int p1;
private int p2;
public ParameterizedTest1(int expected, int p1, int p2) {
this.expected = expected;
this.p1 = p1;
this.p2 = p2;
}
@Test
public void testAdd() {
Calculator calculator = new Calculator();
System.out.println("Addition with parameters : " + p1 + " and "
+ p2);
assertEquals(expected, calculator.add(p1, p2), 0);
}
}
复制代码
定义了一个构造函数,这样就不用功通过Parameter来标记参数的位置。参数的顺序与构造函数的参数顺序一致。这种方法可以将参数用private进行修饰。上述用例计算结果:
通过本文介绍的两种方式,可以很方便的进行参数化测试。