前面我们完成了登录和首页,这篇文章我们将编写性能测试用例管理功能对应的增删改查后台接口,下篇文章完成前端页面的调用。

新建性能测试用例表 performance_case

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for performance_case
-- ----------------------------
DROP TABLE IF EXISTS `performance_case`;
CREATE TABLE `performance_case`  (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `CASE_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `SCRIPT_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `SCRIPT_URL` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `SCRIPT_DATA_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `SCRIPT_DATA_URL` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `PROJECT_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `MODULE_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `OPERATOR` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `CREATE_DATE` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
  `LAST_UPDATE_DATE` timestamp(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0),
  `IS_VALID` tinyint(2) UNSIGNED ZEROFILL NOT NULL DEFAULT 01,
  PRIMARY KEY (`ID`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

编写与表对应的实体类 PerformanceCase

package com.caomingyu.cctestplatform.bean;

import lombok.Data;
import lombok.ToString;

import javax.persistence.*;

@Data
@Entity
@Table(name = "performance_case")
@ToString
public class PerformanceCase extends BaseDomain {
    //主键
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    //用例名
    private String caseName;
    //脚本名
    private String scriptName;
    //脚本存储地址
    private String scriptUrl;
    //脚本数据文件名称(csv文件)
    private String scriptDataName;
    //脚本数据文件存储地址(csv文件)
    private String scriptDataUrl;
    //项目名称
    private String projectName;
    //模块名
    private String moduleName;
    //操作人
    private String operator;
}

pom.xml 引入分页第三方依赖库

<!-- pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.12</version>
</dependency>

编写性能测试用例管理页面的查询接口

1.在持久层接口 PerformanceCaseDao 增加查询方法

package com.syy.testPlatform.dao;

import com.syy.testPlatform.bean.PerformanceCase;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;

@Mapper
public interface PerformanceCaseDao {

    List<PerformanceCase> queryAll(String query);

    PerformanceCase getPerformanceCaseById(Long id);

    void deletePerformanceCaseById(Long id);
}

2.在 PerformanceCaseMapper.xml 增加对应的查询 sql

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.syy.testPlatform.dao.PerformanceCaseDao">
    <resultMap id="BaseResultMap" type="com.syy.testPlatform.bean.PerformanceCase">
        <!--@Table performance_case-->
        <result property="id" column="ID" jdbcType="INTEGER"/>
        <result property="caseName" column="CASE_NAME" jdbcType="VARCHAR"/>
        <result property="scriptName" column="SCRIPT_NAME" jdbcType="VARCHAR"/>
        <result property="scriptUrl" column="SCRIPT_URL" jdbcType="VARCHAR"/>
        <result property="scriptDataName" column="SCRIPT_DATA_NAME" jdbcType="VARCHAR"/>
        <result property="scriptDataUrl" column="SCRIPT_DATA_URL" jdbcType="VARCHAR"/>
        <result property="projectName" column="PROJECT_NAME" jdbcType="VARCHAR"/>
        <result property="moduleName" column="MODULE_NAME" jdbcType="VARCHAR"/>
        <result property="operator" column="OPERATOR" jdbcType="VARCHAR"/>
        <result property="createDate" column="CREATE_DATE" jdbcType="TIMESTAMP"/>
        <result property="lastUpdateDate" column="LAST_UPDATE_DATE" jdbcType="TIMESTAMP"/>
        <result property="isValid" column="IS_VALID" jdbcType="OTHER"/>
    </resultMap>

    <!--通过实体作为筛选条件查询-->
    <select id="queryAll" resultMap="BaseResultMap">
        select
          *
        from performance_case
        where IS_VALID = 1
        <if test="query != null">
            and CASE_NAME like concat('%', #{query}, '%')
        </if>
        order by ID desc
    </select>


    <select id="getPerformanceCaseById" resultMap="BaseResultMap">
        select * from performance_case
        where ID=#{id}
    </select>


    <update id="deletePerformanceCaseById">
        update performance_case set IS_VALID = 0 where ID = #{id}
    </update>

</mapper>

3.编写 PerformanceService,增加对应的查询方法

package com.syy.testPlatform.service;

import com.syy.testPlatform.bean.Result;
import javax.servlet.http.HttpServletRequest;

public interface PerformanceCaseService {
    Result queryAll(Integer pageNum, Integer pageSize, String query);
    Result addTestCase(HttpServletRequest request);
    Result getPerformanceCaseById(Long id);
    Result deletePerformanceCaseById(Long id);
}

4.编写 PerformanceServiceImpl,增加对应的方法

package com.syy.testPlatform.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.syy.testPlatform.bean.Page;
import com.syy.testPlatform.bean.PerformanceCase;
import com.syy.testPlatform.bean.Result;
import com.syy.testPlatform.common.ResultType;
import com.syy.testPlatform.common.StatusCode;
import com.syy.testPlatform.dao.PerformanceCaseDao;
import com.syy.testPlatform.repository.PerformanceCaseRepository;
import com.syy.testPlatform.service.PerformanceCaseService;
import com.syy.testPlatform.util.DateUtils;
import com.syy.testPlatform.util.FileUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;

/**
 * (PerformanceCase)表服务实现类
 *
 * @author makejava
 * @since 2021-04-01 00:47:29
 */
@Service
public class PerformanceCaseServiceImpl implements PerformanceCaseService {
    @Resource
    private PerformanceCaseDao performanceCaseDao;

    @Resource
    private Page pageCustomer;

    @Resource
    private PerformanceCaseRepository PerformanceCaseRepository;


    @Override
    public Result queryAll(Integer pageNum, Integer pageSize, String query) {
        if (pageNum == null){
            pageNum = 1;
        }
        if (pageSize == null){
            pageSize = 10;
        }
        if ("".equals(query)){
            query = null;
        }
        com.github.pagehelper.Page pageInfo = PageHelper.startPage(pageNum, pageSize);
        List<PerformanceCase> performanceCaseList = performanceCaseDao.queryAll(query);
        pageCustomer.setTotal(pageInfo.getTotal());
        pageCustomer.setPageSize(pageInfo.getPageSize());
        pageCustomer.setPageNum(pageInfo.getPageNum());
        pageCustomer.setPages(pageInfo.getPages());
        return Result.resultSuccess(pageCustomer, performanceCaseList, ResultType.GET_PERFORMANCE_TEST_CASE_SUCCESS);
    }


    @Override
    public Result addTestCase(HttpServletRequest request) {
//        MultipartHttpServletRequest params = (MultipartHttpServletRequest) request;
        MultipartHttpServletRequest httpServletRequest = (MultipartHttpServletRequest) request;
        String caseName = httpServletRequest.getParameter("caseName");
        String moduleName = httpServletRequest.getParameter("moduleName");
        String projectName = httpServletRequest.getParameter("projectName");
        String operator = httpServletRequest.getParameter("operator");
        String scriptName = httpServletRequest.getParameter("scriptName");
        String scriptDataName = httpServletRequest.getParameter("scriptDataName");
        String scriptFileArray = httpServletRequest.getParameter("scriptFileArray");
        String scriptDataFileArray = httpServletRequest.getParameter("scriptDataFileArray");
        if (StringUtil.isEmpty(caseName)){
            return Result.resultError(ResultType.CASE_NAME_NULL, StatusCode.CASE_NAME_NULL);
        }
        if (StringUtil.isEmpty(moduleName)){
            return Result.resultError(ResultType.MODULE_NAME_NULL, StatusCode.MODULE_NAME_NULL);
        }
        if (StringUtil.isEmpty(projectName)){
            return Result.resultError(ResultType.PROJECT_NAME_NULL, StatusCode.PROJECT_NAME_NULL);
        }
        if (StringUtil.isEmpty(operator)){
            return Result.resultError(ResultType.OPERATOR_NULL, StatusCode.OPERATOR_NULL);
        }
        if (StringUtil.isEmpty(scriptName)){
            return Result.resultError(ResultType.SCRIPT_NAME_NULL, StatusCode.SCRIPT_NAME_NULL);
        }
        if (!scriptName.toLowerCase().endsWith(".jmx")){
            return Result.resultError(ResultType.WRONG_FILE_FORMAT, StatusCode.WRONG_FILE_FORMAT);
        }

        if (StringUtil.isEmpty(scriptDataFileArray)){
            return Result.resultError(ResultType.FILE_NULL, StatusCode.FILE_NULL);
        }

        StringBuilder realPath = new StringBuilder();
        String scriptUploadBaseuri = "~/Downloads";
        realPath.append(scriptUploadBaseuri).append(DateUtils.getCurrentYear()).append(DateUtils.getCurrentMonth()).append(DateUtils.getCurrentDay()).append(File.separator).append(UUID.randomUUID().toString());
        scriptUploadBaseuri = realPath.toString();
        String scriptPath = scriptUploadBaseuri + scriptName;
        String scriptDataPath = scriptUploadBaseuri + scriptDataName;
        //保存文件
        FileUtil.base64ToFile(scriptPath,scriptFileArray);
        //由于脚本数据文件非必传。所以不需要判空返回错误
        if (!StringUtil.isEmpty(scriptDataFileArray)){
            FileUtil.base64ToFile(scriptDataPath,scriptDataFileArray);
        }
        //保存测试用例数据
        PerformanceCase performanceCase = savePerformanceCase(caseName,moduleName,projectName,operator,scriptName,scriptDataName,scriptPath,scriptDataPath);
        return Result.resultSuccess(null, performanceCase, ResultType.ADD_PERFORMANCE_TEST_CASE_SUCCESS);
    }


    private PerformanceCase savePerformanceCase(String caseName, String moduleName, String projectName, String operator,String scriptName,String scriptDataName, String scriptPath,String scriptDataPath) {
        PerformanceCase performanceCase = new PerformanceCase();
        performanceCase.setCaseName(caseName);
        performanceCase.setModuleName(moduleName);
        performanceCase.setProjectName(projectName);
        performanceCase.setOperator(operator);
        performanceCase.setScriptName(scriptName);
        performanceCase.setScriptDataName(scriptDataName);
        performanceCase.setScriptUrl(scriptPath);
        performanceCase.setScriptDataUrl(scriptDataPath);
        performanceCase.setIsValid(1);
        performanceCase = PerformanceCaseRepository.save(performanceCase);
        return performanceCase;
    }


    @Override
    public Result getPerformanceCaseById(Long id) {
        if (id == null || id.intValue() == 0){
            return Result.resultError(ResultType.CASE_ID_NULL, StatusCode.CASE_ID_NULL);
        }
        PerformanceCase performanceCase = performanceCaseDao.getPerformanceCaseById(id);
        return Result.resultSuccess(null, performanceCase, ResultType.GET_PERFORMANCE_TEST_CASE_SUCCESS);
    }

    @Override
    public Result deletePerformanceCaseById(Long id) {
        if (id == null || id.intValue() == 0){
            return Result.resultError(ResultType.CASE_ID_NULL, StatusCode.CASE_ID_NULL);
        }
        performanceCaseDao.deletePerformanceCaseById(id);
        return Result.resultSuccess(null, null, ResultType.DELETE_PERFORMANCE_TEST_CASE_SUCCESS);
    }

}

5.编写 PerformanceController,增加对应的接口

package com.syy.testPlatform.controller;

import com.syy.testPlatform.bean.Result;
import com.syy.testPlatform.service.PerformanceCaseService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * (PerformanceCase)表控制层
 *
 * @author makejava
 * @since 2021-04-01 00:47:29
 */
@RestController
@RequestMapping("/api/v1/performance")
public class PerformanceCaseController {
    /**
     * 服务对象
     */
    @Resource
    private PerformanceCaseService PerformanceCaseService;

    //根据搜索字符串从数据库查询出对应的测试用例数据,如果为空则默认查全部
    @GetMapping("/queryAll")
    public Result queryAll(@RequestParam(value="pageNum") Integer pageNum, @RequestParam (value="pageSize") Integer pageSize, @RequestParam (value="query") String query){
        return PerformanceCaseService.queryAll(pageNum, pageSize,query);
    }


    //添加测试用例
    @PostMapping("/addTestCase")
    public Result addTestCase(HttpServletRequest request){
        return  PerformanceCaseService.addTestCase(request);
    }


    //根据id获取测试用例,用于编辑窗口回显数据
    @GetMapping("/getPerformanceCase/{id}")
    public Result getPerformanceCaseById(@PathVariable Long id) {
        return PerformanceCaseService.getPerformanceCaseById(id);
    }

    @GetMapping("/deletePerformanceCase/{id}")
    public Result deletePerformanceCaseById(@PathVariable Long id) {
        return PerformanceCaseService.deletePerformanceCaseById(id);
    }

}

编写性能测试用例管理页面的添加/编辑 用例接口

1.增加 jpa 相关接口类 PerformanceCaseRepository

package com.syy.testPlatform.repository;

import com.syy.testPlatform.bean.PerformanceCase;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PerformanceCaseRepository extends JpaRepository<PerformanceCase,Long> {
}

工具类 FileUtil

package com.syy.testPlatform.util;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Base64;

public class FileUtil {
    //BASE64解码成File文件
    public static void base64ToFile(String filePath,String base64) {
        if (base64.contains(",")){
            base64 = base64.split(",")[1];
        }

        File file = new File(filePath);
        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try (FileOutputStream fos = new java.io.FileOutputStream(file);
             BufferedOutputStream bos = new BufferedOutputStream(fos);) {
            byte[] bytes = Base64.getDecoder().decode(base64);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


↙↙↙阅读原文可查看相关链接,并与作者交流