在某些状况下,为了更全面的测试,咱们须要构建多组数据对目标对象进行更全面的测试,普通的作法就有点繁琐。
java
junit能够是这种状况参数化,只要定义好参数结构便可。sql
这里用到@Parameters注解,放在一个public static方法上,并返回所需的参数集合;另外测试类上加@RunWith(Parameterized.class)。实例代码以下:函数
待测试类:测试
public class Calculate { /** * 计算:返回两个整数的和 * * @param first * @param second * @return */ public int sum(int first, int second) { return first + second; } }
测试类以下:this
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 CalculateTest { private int expected; private int first; private int second; private Calculate calculate = new Calculate(); public CalculateTest(int expected, int first, int second) { super(); this.expected = expected; this.first = first; this.second = second; } @Parameters public static Collection<Integer[]> testDatas() { // 测试参数:和构造函数中参数的位置一一对应。 return Arrays.asList(new Integer[][] { { 3, 2, 1 }, { 5, 3, 2 }, { 7, 6, 1 } }); } @Test public void testSum() { System.out.println("测试:" + first + "+" + second); assertEquals(expected, calculate.sum(first, second)); } }
从输出能够看出testSum()跑了三遍,输出以下:spa
测试:2+1 测试:3+2 测试:6+1