在某些情况下,为了更全面的测试,我们需要构建多组数据对目标对象进行更全面的测试,普通的做法就有点繁琐。
junit可以是这种情况参数化,只要定义好参数结构即可。
这里用到@Parameters注解,放在一个public static方法上,并返回所需的参数集合;另外测试类上加@RunWith(Parameterized.class)。实例代码如下:
待测试类:
public class Calculate {
/**
* 计算:返回两个整数的和
*
* @param first
* @param second
* @return
*/
public int sum(int first, int second) {
return first + second;
}
}
测试类如下:
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()跑了三遍,输出如下:
测试:2+1
测试:3+2
测试:6+1