通过注解来绑定测试参数
package testPacage;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class Test04Test2 {
Test04 t = new Test04();
@Parameter(value = 0)
public String lett;
@Parameter(value = 1)
public String result;
@Parameters
public static Collection data() {
return Arrays.asList(new Object[][] {{"ab123", "替换前缀后的字符串为:ef123"},
{"32cd1cd", "替换cd后的字符串为:32gh1gh"},
{"ab123cd", "大写字母的字符串为:AB123CD"}});
}
@Test
public void test() {
Assert.assertEquals(result, t.testFun(lett));
System.out.println("result = " + result);
}
}
参数化测试的必要部分:
- @RunWith(Parameterized.class),表示在测试方法类上
- @Parameters,表示在参数列表方法上
- 参数列表方法,必须返回Collection类型,必须是static修饰的静态方法,将被测方法的入参和预期结果依次填入数组中(保持前后顺序)
- @Parameter(value = ),使用注解绑定测试参数,value表示索引,从0开始,如:参数列表方法中有{"abc","字符:abc"},前者是入参,后者是预期结果,则
@Parameter(value = 0) public String chars; @Parameter(value = 1) public String result;
- 切记,使用注解绑定测试参数时,变量一定使用public修饰
- 使用断言时就可以直接使用定义好的参数了
通过构造函数来绑定测试参数
package testPacage;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Assert;
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 Test04Test2 {
Test04 t = new Test04();
private String lett;
private String result;
public Test04Test2(String lett, String result){
this.lett = lett;
this.result = result;
}
@Parameters
public static Collection data() {
return Arrays.asList(new Object[][] {{"ab123", "替换前缀后的字符串为:ef123"},
{"32cd1cd", "替换cd后的字符串为:32gh1gh"},
{"ab123cd", "大写字母的字符串为:AB123CD"}});
}
@Test
public void test() {
Assert.assertEquals(result, t.testFun(lett));
System.out.println("result = " + result);
}
}
- 新建构造函数,入参的顺序要与参数列表方法中的顺序一样
- 后续的使用方法同上