JUnit 4中引入了参数化测试功能,支持使用不同的测试数据反复执行同一个测试类中的测试方法。可以极大提高测试开发效率,降低代码重复度。
参数化测试的5个基本步骤:
- 使用
@RunWith(Parameterized.class)
注解测试类。 - 在测试类中创建一个使用
@Parameters
注解的公共静态方法,并返回一个包含测试数据对象的集合。 - 创建一个测试类的公共构造函数,其接受的入参和测试数据对象相互对应。
- 编写测试方法,测试方法中可以使用测试类的变量(变量数据来自构造函数接受的测试数据)。
- JUnit执行测试时,自动会为测试数据对象集合中的每一列数据创建一个测试实例,测试实例中的变量会作为测试方法的测试数据来源。
示例程序:
被测代码:HelloWorld.java
public class HelloWorld {
public String sayHello(String name) {
return "hello:" + name;
}
}
测试代码:HelloWorldBatchTest.java
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;
@RunWith(Parameterized.class)
public class HelloWorldBatchTest {
private String name;
private String expected;
public HelloWorldBatchTest(String name, String expected){
this.name = name;
this.expected = expected;
}
@Parameters
public static Collection<Object[]> initTestData(){
return Arrays.asList(new Object[][] {
{"world", "hello:world"},
{"", "hello:"},
{null, "hello:null"},
{"!@#$%^&*()_+", "hello:!@#$%^&*()_+"}
});
}
@Test
public void testSayHello() {
HelloWorld helloWorld = new HelloWorld();
assertEquals(this.expected, helloWorld.sayHello(this.name));
}
}
使用mvn test
命令执行测试:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running HelloWorldBatchTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.12 sec
Results :
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0