JUnit参数化设置-- 增加代码的重用性
步骤:(来自慕课网)
1.更改默认的测试运行器为RunWith(Parameterized.class)
2.声明变量来存放预期值和结果值
3.声明一个返回值为Collection的公共静态方法,并使用@Parameters进行修饰
4.为测试类声明一个带有参数的公共构造方法,并在其中为之声明变量赋值
一个小例子:
package com.junit01.model;
import static org.junit.Assert.*;
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;
//1、更改运行器i
@RunWith(Parameterized.class)
public class ParaTest {
//2、声明变量存放期望值和参数值
int expected = 0;
int input1 = 0;
int input2 = 0;
//3、声明一个返回值为Collection的公共静态方法,并使用Parameters修饰
@Parameters
public static Collection<Object[]> t(){
return Arrays.asList(new Object[][]{
{3,1,2},
{7,4,3}
});
}
//构造方法,给期望值和参数值赋值
//4.为测试类声明一个带有参数的公共构造方法,并在其中为之声明变量赋值
public ParaTest(int expected, int input1, int input2){
this.expected = expected;
this.input1 = input1;
this.input2 = input2;
}
@Test
public void test() {
assertEquals(expected, new HelloJunit().add(input1, input2));
}
}
测试结果: