JUNIT自动化测试
需求:对同一个方法,设置一组不同的参数,自动化测试
下载idea插件
file->settings->Plugins,搜索junit
,点击下载第一个插件JUnitGenerator
添加依赖
pom.xml文件中添加
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
添加test文件夹
new->Directory,选择Maven Source Directories
,点击绿色标识的src\test\java
编写测试类
@Before
初始化测试方法所在的类
@Parameterized.Parameters
参数列表
@Test
测试方法,依次运行参数列表
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
/**
* 使用@RunWith(Parameterized.class)注释测试类。
* 创建一个使用@Parameters注释的公共静态方法,该方法返回一个对象集合作为测试数据集。
* 创建一个公共构造函数,它接受相当于一行“测试数据”的内容。
* 为测试数据的每个“列”创建一个实例变量。
* 使用实例变量作为测试数据的来源创建测试用例。
*/
@RunWith(Parameterized.class)
public class ClusterTest {
private double gridwith;
private double eps;
private int minpts;
private Cluster cluster;
@Before
public void initialize() {
cluster = new Cluster();
}
public ClusterTest(double gridwith,
double eps,
int minpts) {
this.gridwith = gridwith;
this.eps = eps;
this.minpts = minpts;
}
@Parameterized.Parameters
public static Collection paras() {
return Arrays.asList(new Object[][] {
{ 25.0, 30.0, 15},
{ 30.0, 30.0, 15},
{ 35.0, 30.0, 15}
});
}
@Test
public void testCluster() throws Exception {
System.out.println("Parameterized Number is : " + gridwith + "/" + eps + "/" + minpts);
cluster.paraParameterizedCluster(gridwith, eps, minpts);
}
}
编写测试运行类
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
/**
* Created with IntelliJ IDEA.
*
* @author lmy
* @create 2022-04-24 19:37
* @Description: No Description
*/
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(ClusterTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
被测类
public class Cluster {
private static double gridWidth = 50.d; // 网格半径
private static double eps = 150; // 邻域半径
private static int minPts = 25; // 密度阈值
...
public void paraParameterizedCluster(double gridWidth, double eps, int minPts) throws Exception {
this.gridWidth = gridWidth;
this.eps = eps;
this.minPts = minPts;
....
}
}
报错&解决
运行TestRunner.main()
,报错Java.lang.Exception: No runnable methods
@Test导入了org.junit.jupiter.api.Test
,改正为org.junit.Test