Junit5使用CsvFileSource创建csv文件进行参数化测试

一、创建工程,建一个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

最后运行测试类即可,如下:
在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

村头卖假发的小郑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值