对于一个方法须要进行多种场景进行测试时,能够经过参数化测试减小测试的工做量。用法以下:java
1 package junit.util; 2 3 import static org.junit.Assert.assertEquals; 4 5 import java.util.Arrays; 6 import java.util.Collection; 7 8 import org.junit.Test; 9 import org.junit.runner.RunWith; 10 import org.junit.runners.Parameterized; 11 import org.junit.runners.Parameterized.Parameters; 12 13 @RunWith(Parameterized.class) 14 public class ParameterTest { 15 16 /** 17 * 一、更改测试运行器为RunWith(Parameterized.class) 18 * 二、声明变量用来存放预期值与结果值 19 * 三、声明一个返回值为Collection的公共静态方法,并使用@Parameters进行修饰 20 * 四、位测试类声明一个带有参数的公共构造方法,并在其中为声明变量赋值 21 */ 22 23 int except; //用来存储预期结果 24 int input1; //用来存储第一个输入参数 25 int input2; //用来存储第二个输入参数 26 27 @Parameters 28 public static Collection<Object[]> initTestData(){ 29 return Arrays.asList( 30 new Object[][]{ 31 {3,1,2}, 32 {10,5,5}, 33 {6,4,2}, 34 {7,3,4}} 35 ); 36 } 37 38 public ParameterTest(int except,int input1,int input2){ 39 this.except = except; 40 this.input1 = input1; 41 this.input2 = input2; 42 } 43 44 45 46 47 48 @Test 49 public void testAdd() { 50 assertEquals(except, new Claculate().add(input1, input2)); 51 } 52 53 }