springboot使用h2数据库对dao层进行单元测试

springboot使用h2数据库对dao层(mybatis)进行单元测试

此博客用于记录项目对dao层进行操作数据库的单元测试走过的坑,因为考虑到程序员自己进行白盒测试,如果直接操作数据库(虽然也是测试数据库),但会扰乱测试人员辛苦制造的数据,所以直接使用h2内存数据库进行测试。这是我入职的第一份任务,给原有项目写单元测试。

一、h2的配置

  1. 创建配置文件test/resource/applicationContext.xml
    applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">

    <!-- 扫描属性文件 -->
    <context:property-placeholder location="classpath*:application.properties" />

    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${spring.datasource.driverClassName}" />
        <property name="url" value="${spring.datasource.url}" />
        <property name="username" value="${spring.datasource.username}" />
        <property name="password" value="${spring.datasource.password}" />
    </bean>

    <jdbc:initialize-database data-source="dataSource" ignore-failures="DROPS">
        <jdbc:script location="${spring.datasource.schema}" />
        <jdbc:script location="${spring.datasource.data}" /> 
    </jdbc:initialize-database>
</beans>

在这里插入图片描述

  1. 创建属性文件application.properties
    application.properties:
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:databaseName(注:此处改成你的数据库名字)
spring.datasource.username=sa
spring.datasource.password=
# 打印 SQL语句, Mapper所处的包
logging.level.com.pdd.service.refund.repository.repositoryV2=debug

二、将sql文件导入到h2数据库

如下图所示,是从mysql数据库中导出sql,但不能直接h2数据库执行,因为sql中有很多mysql的关键字在h2中不支持,即无法识别(虽然直接放到h2的console中可以执行,但在测试环境中直接跑脚本就会报错)。我一晚上就在折腾h2的sql导入问题,,,
(2019.7.12修订)

  • 图中1,3-5框起来的代码都必须删除,因为在h2数据库中没有这些关键字;2中defaut关键字是支持的,经过测试
  • 图6的箭头是提示,在sql文件的最后那个create table的结尾必须添加标点符号------";" ;
  • 最后补充一点,不需要在schme.sql中添加创建数据库的sql语句。我想在程序连接h2的时候,h2会判断是否存在你连接的库,如果没有会自动创建这个库。
-- drop database if exists `databaseName`;
-- create database `databaseName`;
-- use `databaseName`;

在这里插入图片描述

发布了151 篇原创文章 · 获赞 104 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/qq_35923749/article/details/95381837