Parameterized (参数化)的测试运行器允许你使用不同的参数多次运行同一个侧试。
运行此测试的必备条件:
1.必须使用@RunWith(Parameterized.class)
2.必须声明测试用到的变量
3.提供一个@Parameterized注解的方法
例如:
public class Calculator {
public double add(double i,double j){
return i+j;
}
}
package com.laoxu.gamedog.util;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.*;
/**
* 参数化测试
*
* @author xusucheng
* @create 2018-12-16
**/
@RunWith(Parameterized.class)
public class ParameterizedTest {
private double expected;
private double p1;
private double p2;
@Parameterized.Parameters
public static Collection<Integer[]> getTestParamters() {
return Arrays.asList(new Integer[][]{
{2, 1, 1}, {3, 2, 1}, {4, 3, 1}
});
}
public ParameterizedTest(double expected, double p1, double 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);
}
}
运行结果:
Addition with parameters : 1.0 and 1.0
Addition with parameters : 2.0 and 1.0
Addition with parameters : 3.0 and 1.0
说明运行了3次!
参数化测试实战

本文详细介绍如何使用Parameterized测试运行器进行参数化测试,通过实例演示如何设置测试参数,运行多次同一测试以验证不同输入情况下的行为。适用于JUnit框架使用者。
966

被折叠的 条评论
为什么被折叠?



