一、创建工程,建一个maven项目
二、导入Junit5的依赖,自动导入包
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
<!-- Parameterized Tests -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
</dependencies>
如果这里添加依赖后没有自动导入,可以重新载入配置文件,步骤如下。
等待项目重新启动即可。。。
三、编写Insurance类代码,即我们要测试的类
package com.ctgu.zyj.insurance;
public class Insurance {
private static final int Basic_PREMIUM_RATE = 1000;
private static final int[][] SETTING = {{0,0,0},{28,11,50},{18,9,100},{10,7,150},{8,5,200},{15,7,250}};
public static int[] calcSetting(int age){
if (age < 16 || age >80){
return SETTING[0];
}else if(age < 25){
return SETTING[1];
}else if(age < 35){
return SETTING[2];
}else if (age <45){
return SETTING[3];
}else if (age < 60){
return SETTING[4];
}else {
return SETTING[5];
}
}
public int calcInsurance(int age,int score){
int insuranceMoney = -1;
if(score > 0 && score<13){
int[] setting = calcSetting(age);
if (setting!=SETTING[0]){
int safeDrivingDiscount = 0;
int ageCoeffcient = setting[0];
int scoreThreshold = setting[1];
if (score>scoreThreshold){
safeDrivingDiscount = setting[2];
}
insuranceMoney = (int)(Basic_PREMIUM_RATE/10*ageCoeffcient)-safeDrivingDiscount;
}
}
return insuranceMoney;
}
}
按住ctrl + shift + T,自动生成测试类如下:
测试代码类的代码如下:
package com.ctgu.zyj.insurance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;
import static org.junit.jupiter.api.Assertions.*;
class InsuranceTest {
Insurance insurance = new Insurance();
@ParameterizedTest
@CsvFileSource(resources = "/test.csv")
void calcInsurance(int age,int score,int money) {
assertEquals(money,insurance.calcInsurance(age,score));
}
}
四、创建csv文件,进行参数化测试
测试数据如下:
20,12,2750
20,6,2800
30,11,1700
30,5,1800
40,10,850
40,4,1000
52,9,600
52,3,800
70,10,1250
70,4,1500
最后运行测试类即可,如下: