概述
项目场景:
编写代码单元测试为了保证测试环境数据稳定性,使用内嵌数据库H2来代替测试环境数据库
前提:
需注意MySQL导出的sql文件无法适用于H2,具体转换方式详见 https://blog.csdn.net/qionglong_jiao/article/details/117298689
项目准备:
H2建表语句:schema.sql
-- ----------------------------
-- Table structure for app_alarm_year_statistic_single
-- ----------------------------
DROP TABLE IF EXISTS app_alarm_year_statistic_single;
CREATE TABLE app_alarm_year_statistic_single
(
id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '序号',
vin varchar(17) NOT NULL COMMENT 'vin码',
oem varchar(20) NULL DEFAULT NULL COMMENT '整车厂',
brand varchar(20) NULL DEFAULT NULL COMMENT '品牌',
car_type varchar(20) NULL DEFAULT NULL COMMENT '车型',
st_date char(8) NULL DEFAULT NULL COMMENT '数据日期(yyyyMMdd)',
running_year tinyint(10) UNSIGNED NULL DEFAULT NULL COMMENT '使用年数',
all_alarm_sum bigint(255) UNSIGNED NULL DEFAULT NULL COMMENT '所有报警数_总条数',
temp_diff_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT '温度差异报警_总条数',
over_temp_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT '电池高温报警_总条数',
over_voltage_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT '电池过压报警_总条数',
under_voltage_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT '电池欠压报警_总条数',
soc_low_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT 'SOC低报警_总条数',
cell_over_voltage_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT '单体电池过压报警_总条数',
cell_under_voltage_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT '单体电池欠压报警_总条数',
soc_high_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT 'SOC过高报警_总条数',
soc_transition_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT 'SOC跳变报警_总条数',
poor_consistency_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT '单体一致性差报警_总条数',
insulation_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT '绝缘报警_总条数',
over_charging_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT '电池过充报警_总条数',
first_level_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT '一级报警_总条数',
second_level_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT '二级报警_总条数',
third_level_alarm_sum int(255) UNSIGNED NULL DEFAULT NULL COMMENT '三级报警_总条数',
create_datetime datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间',
update_datetime datetime NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '记录更新时间',
PRIMARY KEY (id)
);
H2表数据:data.sql
-- ----------------------------
-- Records of app_alarm_year_statistic_single
-- ----------------------------
DELETE FROM app_alarm_year_statistic_single;
INSERT INTO app_alarm_year_statistic_single VALUES (1, '123', 'BAIC', 'BEIJING', 'B01', '20210505', 1, 100, 1, 2, 3, 4, 5, 5, 5, 5, 4, 5, 54, 4, 4, 54, 35, '2021-05-11 15:51:37', '2021-05-14 14:06:27');
INSERT INTO app_alarm_year_statistic_single VALUES (2, '123', 'BAIC', 'BEIJING', 'B01', '20210505', 2, 100, 1, 3, 3, 3, 34, 243, 235, 3, 325, 234, 32, 23, 32, 432, 43, '2021-05-11 15:51:37', '2021-05-14 14:06:15');
INSERT INTO app_alarm_year_statistic_single VALUES (3, '123', 'BAIC', 'BEIJING', 'B01', '20210505', 3, 100, 1, 3, 3, 3, 34, 243, 235, 3, 325, 234, 32, 23, 32, 432, 43, '2021-05-11 15:51:37', '2021-05-14 14:06:16');
INSERT INTO app_alarm_year_statistic_single VALUES (4, '1234', 'BAIC', 'BEIJING', 'B01', '20210505', 3, 100, 1, 3, 3, 3, 34, 243, 235, 3, 325, 234, 32, 23, 32, 432, 43, '2021-05-11 15:51:37', '2021-05-14 14:06:18');
使用内嵌数据库H2:
创建springboot项目
引入依赖:
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--h2数据库驱动-->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
application.yml
spring:
datasource:
driver-class-name: org.h2.Driver
schema: classpath:db/schema.sql #每次启动程序,程序都会运行schema.sql文件,对数据库的数据操作
data: classpath:db/data.sql #每次启动程序,程序都会运行data.sql文件,对数据库的数据操作
url: jdbc:h2:mem:test #配置h2数据库的连接地址
username: test
password: test
创建实体类:
package com.uaes.battery.fault.monitoring.statistics.domain;
import lombok.Data;
@Data
public class AppAlarmYearStatisticSingleDAO {
private String vin;
private String oem;
private String brand;
private String carType;
private Integer runningYear;
private Integer allAlarm;
private Integer cellVolOver;
private Integer cellVolLow;
private Integer batteryBadConsistency;
private Integer socOver;
private Integer socLow;
private Integer socJump;
private Integer batteryOver;
private Integer batteryLow;
private Integer batteryTempOver;
private Integer tempDiff;
private Integer insulation;
private Integer ressChargeOver;
private Integer totalVehicle;
}
创建持久层:
package com.uaes.battery.fault.monitoring.statistics.mapper;
import com.uaes.battery.fault.monitoring.statistics.domain.AppAlarmYearStatisticSingleDAO;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface AppAlarmYearStatisticSingleMapper {
/*
* 根据条件查询单车故障按照年份的统计结果
* */
List<AppAlarmYearStatisticSingleDAO> selectAlarmStatistic(@Param("vin") String vin,
@Param("stDate") String stDate);
}
持久层实现:
<?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.uaes.battery.fault.monitoring.statistics.mapper.AppAlarmYearStatisticSingleMapper">
<select id="selectAlarmStatistic"
resultType="com.uaes.battery.fault.monitoring.statistics.domain.AppAlarmYearStatisticSingleDAO">
SELECT
vin,
oem,
brand,
car_type,
running_year AS runningYear,
all_alarm_sum AS allAlarm,
cell_over_voltage_alarm_sum AS cellVolOver,
cell_under_voltage_alarm_sum AS cellVolLow,
poor_consistency_alarm_sum AS batteryBadConsistency,
soc_high_alarm_sum AS socOver,
soc_low_alarm_sum AS socLow,
soc_transition_alarm_sum AS socJump,
over_voltage_alarm_sum AS batteryOver,
under_voltage_alarm_sum AS batteryLow,
over_temp_alarm_sum AS batteryTempOver,
temp_diff_alarm_sum AS tempDiff,
insulation_alarm_sum AS insulation,
over_charging_alarm_sum AS ressChargeOver
FROM
app_alarm_year_statistic_single
WHERE
vin = #{vin}
<choose>
<when test="stDate == null">
AND st_date = (
SELECT
MAX(st_date)
FROM
app_alarm_year_statistic_single
WHERE
vin = #{vin}
)
</when>
<otherwise>
AND st_date = #{stDate}
</otherwise>
</choose>
</select>
</mapper>
测试类:
package com.uaes.battery.fault.monitoring.statistics.mapper;
import com.alibaba.fastjson.JSONObject;
import com.uaes.battery.fault.monitoring.statistics.domain.AppAlarmYearStatisticSingleDAO;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@SpringBootTest
@RunWith(SpringRunner.class)
public class AppAlarmYearStatisticSingleMapperTest {
@Autowired
private AppAlarmYearStatisticSingleMapper appAlarmYearStatisticSingleMapper;
@Test
public void selectAlarmStatistic() {
List<AppAlarmYearStatisticSingleDAO> list =appAlarmYearStatisticSingleMapper.selectAlarmStatistic("123",null);
System.out.println(JSONObject.toJSON(list));
}
}
测试结果:
[{"batteryTempOver":2,"cellVolOver":5,"socLow":5,"ressChargeOver":4,"insulation":54,"tempDiff":1,"carType":"B01","allAlarm":100,"socOver":5,"batteryBadConsistency":5,"batteryOver":3,"cellVolLow":5,"oem":"BAIC","runningYear":1,"socJump":4,"batteryLow":4,"vin":"123","brand":"BEIJING"},{"batteryTempOver":3,"cellVolOver":243,"socLow":34,"ressChargeOver":23,"insulation":32,"tempDiff":1,"carType":"B01","allAlarm":100,"socOver":3,"batteryBadConsistency":234,"batteryOver":3,"cellVolLow":235,"oem":"BAIC","runningYear":2,"socJump":325,"batteryLow":3,"vin":"123","brand":"BEIJING"},{"batteryTempOver":3,"cellVolOver":243,"socLow":34,"ressChargeOver":23,"insulation":32,"tempDiff":1,"carType":"B01","allAlarm":100,"socOver":3,"batteryBadConsistency":234,"batteryOver":3,"cellVolLow":235,"oem":"BAIC","runningYear":3,"socJump":325,"batteryLow":3,"vin":"123","brand":"BEIJING"}]
至此说明我们的H2内嵌数据库已经可以代替MySQL跑通持久层的单元测试
Mockito
service:
package com.uaes.battery.fault.monitoring.statistics.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.uaes.battery.fault.monitoring.statistics.domain.*;
import com.uaes.battery.fault.monitoring.statistics.mapper.AppAlarmYearStatisticSingleMapper;
import com.uaes.battery.fault.monitoring.statistics.service.AppAlarmYearStatisticSingleService;
import com.uaes.battery.fault.monitoring.statistics.util.ReturnUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class AppAlarmYearStatisticSingleServiceImpl implements AppAlarmYearStatisticSingleService {
@Autowired
private AppAlarmYearStatisticSingleMapper appAlarmYearStatisticSingleMapper;
@Override
public Object selectYearAlarmSum(String vin, String stDate) {
JSONObject result = new JSONObject();
List<AppAlarmYearStatisticSingleDAO> list = appAlarmYearStatisticSingleMapper.selectAlarmStatistic(vin, stDate);
if (null != list) {
ReturnUtil.bulidReturnDataSingle(result, list.get(0).getVin(), list.get(0).getOem(), list.get(0).getBrand(), list.get(0).getCarType(), stDate);
Map<Integer, AppAlarmYearStatisticSingleDTO> alarmValueMap = list.stream().collect(Collectors.toMap(AppAlarmYearStatisticSingleDAO::getRunningYear, a -> new AppAlarmYearStatisticSingleDTO(a), (k1, k2) -> k2));
result.put("alarmValue", JSONObject.toJSON(alarmValueMap));
}
return result;
}
}
serviceTest:
package com.uaes.battery.fault.monitoring.statistics.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.uaes.battery.fault.monitoring.statistics.domain.AppAlarmYearStatisticSingleDAO;
import com.uaes.battery.fault.monitoring.statistics.mapper.AppAlarmYearStatisticSingleMapper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.List;
@RunWith(MockitoJUnitRunner.class)
public class AppAlarmYearStatisticSingleServiceImplTest {
@InjectMocks
private AppAlarmYearStatisticSingleServiceImpl appAlarmYearStatisticSingleService;
@Mock
private AppAlarmYearStatisticSingleMapper appAlarmYearStatisticSingleMapper;
@Test
public void selectYearAlarmSum() {
// 模拟appAlarmYearStatisticSingleMapper.selectAlarmStatistic("", ""))的返回值为thenReturn
List<AppAlarmYearStatisticSingleDAO> thenReturn = JSONArray.parseArray("[{"batteryTempOver":2,"cellVolOver":5,"socLow":5,"ressChargeOver":4,"insulation":54,"tempDiff":1,"carType":"B01","allAlarm":100,"socOver":5,"batteryBadConsistency":5,"batteryOver":3,"cellVolLow":5,"oem":"BAIC","runningYear":1,"socJump":4,"batteryLow":4,"vin":"123","brand":"BEIJING"},{"batteryTempOver":3,"cellVolOver":243,"socLow":34,"ressChargeOver":23,"insulation":32,"tempDiff":1,"carType":"B01","allAlarm":100,"socOver":3,"batteryBadConsistency":234,"batteryOver":3,"cellVolLow":235,"oem":"BAIC","runningYear":2,"socJump":325,"batteryLow":3,"vin":"123","brand":"BEIJING"},{"batteryTempOver":3,"cellVolOver":243,"socLow":34,"ressChargeOver":23,"insulation":32,"tempDiff":1,"carType":"B01","allAlarm":100,"socOver":3,"batteryBadConsistency":234,"batteryOver":3,"cellVolLow":235,"oem":"BAIC","runningYear":3,"socJump":325,"batteryLow":3,"vin":"123","brand":"BEIJING"}]",AppAlarmYearStatisticSingleDAO.class );
Mockito.when(appAlarmYearStatisticSingleMapper.selectAlarmStatistic("", "")).thenReturn(thenReturn);
// 构建actual
Object actual = JSON.parseObject("{"carType":"B01","alarmValue":{"1":{"batteryTempOver":2,"cellVolOver":5,"socLow":5,"ressChargeOver":4,"insulation":54,"tempDiff":1,"allAlarm":100,"socOver":5,"batteryBadConsistency":5,"batteryOver":3,"cellVolLow":5,"socJump":4,"batteryLow":4},"2":{"batteryTempOver":3,"cellVolOver":243,"socLow":34,"ressChargeOver":23,"insulation":32,"tempDiff":1,"allAlarm":100,"socOver":3,"batteryBadConsistency":234,"batteryOver":3,"cellVolLow":235,"socJump":325,"batteryLow":3},"3":{"batteryTempOver":3,"cellVolOver":243,"socLow":34,"ressChargeOver":23,"insulation":32,"tempDiff":1,"allAlarm":100,"socOver":3,"batteryBadConsistency":234,"batteryOver":3,"cellVolLow":235,"socJump":325,"batteryLow":3}},"oem":"BAIC","vin":"123","brand":"BEIJING","stDate":""}");
Assert.assertEquals(appAlarmYearStatisticSingleService.selectYearAlarmSum("", ""),actual);
}
}
mockito常用方法:
至此一个简要的测试用例已经完成。
最后
以上就是清爽舞蹈为你收集整理的Springboot+H2+Mockito 单元测试,脱离外部MySQL连接项目场景:的全部内容,希望文章能够帮你解决Springboot+H2+Mockito 单元测试,脱离外部MySQL连接项目场景:所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复