单元测试之h2数据库的快速使用!(附实例)

假设你现在是有一个能够链接数据库的项目,而你现在想用h2数据库去单元测试,那么下面几个步骤是你应该做的!(另外不想跟着步骤做的直接去我github上把实例clone下来自己看也行)

1.pom

加入h2依赖

 <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.197</version>
            <scope>runtime</scope>
        </dependency>

2.加入数据库表结构与表数据的sql文件

在这里插入图片描述
我的表结构非常简单:这是我的表结构sql文件(schema.sql),注意的地方是,charset尽量用utf-8,前面我这里用的是latin,结果直接报错,应该是h2不支持这种charset:
在这里插入图片描述
这是我的数据文件(data.sql):
在这里插入图片描述

3.在application.properties文件中添加:

logging.level.van.unittest.test.dao=debug
#在日志里面显示出执行的sql语句,logging.level.具体的包名

#配置数据库连接地址
spring.datasource.url: jdbc:h2:mem:zwt_feedback;MODE=MySQL;
#配置数据库驱动
spring.datasource.driver-class-name: org.h2.Driver
#配置数据库用户名
spring.datasource.username: root
#配置数据库密码
spring.datasource.password: root
#配置能远程访问
spring.h2.console.settings.web-allow-others: true
#配置访问地址
spring.h2.console.path: /h2-console
#配置项目启动 h2就启动
spring.h2.console.enabled: true
#进行该配置后,每次启动程序,程序都会运行resources/db/schema.sql文件,对数据库的结构进行操作。
spring.datasource.schema: classpath:sql/schema.sql
#进行该配置后,每次启动程序,程序都会运行resources/db/data.sql文件,对数据库的数据操作。
spring.datasource.data: classpath:sql/data.sql

自己只要改这里就行了:
在这里插入图片描述
我试了一下,什么用户名,密码,配置访问地址,随便填都可以.并不影响!
下面是demo演示,自己选择http或ssh来克隆吧(ssm是spring的demo,另一个是springboot的demo)

git clone https://github.com/vanNo1/h2-springboot-ssm.git

git clone [email protected]:vanNo1/h2-springboot-ssm.git

猜你喜欢

转载自blog.csdn.net/weixin_44841849/article/details/107593740