使用Junit做参数化测试

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/liuchuanhong1/article/details/78044715

很多时候,我们在开发中写单元测试的时候,当对同一个方法的不同边界取值时,需要写多个单元测试来达到分支覆盖的效果,例如测试两个数相除,至少需要测试以下几个情况:

1、被除数为0的情况

2、除数为整数的情况

3、除数为小数的情况

所以,我们至少需要写三个单元测试。

下面来介绍一下使用Junit来进行参数化的测试,可以通过批量构建测试参数,从而达到全覆盖的目的,首先还是来先看一段代码:

import static org.junit.Assert.assertEquals;
 
import java.util.Arrays;
import java.util.Collection;
 
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
 
// 该RunWith是参数化测试特有的
@RunWith(Parameterized.class)
public class Parameter {
private int expected;// 期望的结果
private int input1;// 除数
private int input2;// 被除数
private static Div div = null;// 两个数相除的方法
/**
 * 构造函数,用来赋值
 * @param expected
 * @param input1
 * @param input2
 */
public Parameter(int expected, int input1, int input2){
this.expected = expected;
this.input1 = input1;
this.input2 = input2;
}
@Before
public void before(){
div = new Div();
System.out.println("Step into Before!");
}
/**
 * @return
 */
@SuppressWarnings("unchecked")
@Parameters// 构造测试用例
public static Collection data(){
return Arrays.asList(new Object[][]{{2,4,2},{3,6,2},{4,8,2}});
}
@Test
public void testParamtersDiv() throws InterruptedException{
int result = div.Divsion(this.input1, this.input2);
assertEquals(this.expected, result);
}
}

参数化的测试需要满足一下几个条件:

1. 测试类必须由Parameterized测试运行器修饰 
2. 准备数据。数据的准备需要在一个方法中进行,该方法需要满足一定的要求: 
  1)该方法必须由Parameters注解修饰 
  2)该方法必须为public static的 
  3)该方法必须返回Collection类型 
  4)该方法的名字不做要求 
  5)该方法没有参数 

上面的代码中public static Collection data()用来准备测试数据。构造函数用来为每个参数赋值。

需要注意一点的是,如果我们将上面的所有代码写在一个测试类里面,是会报错的,因为使用Junit进行普通的测试和进行参数化的测试是不同的,主要是因为使用的@RunWith不同,普通的测试使用的是默认的,而参数化的测试使用的是@RunWith(Parameterized.class)。两者的测试环境和测试需要的条件都不相同。

猜你喜欢

转载自blog.csdn.net/liuchuanhong1/article/details/78044715