为了让兄弟们快速介入单元测试的基本使用,整理了一系列不同场景的,基于SpringBoot的单元测试Demo,并梳理一下相关使用过程和注意事项。
首先是数据库,本文基于JPA进行说明,开发使用MySql,单元测试使用H2数据库。
这样,单元测试可以在Jenkins构建环境或其它管道模式下运行,便于业务的正确性测试和覆盖率检测。
相关代码已经放在Github上:源代码
下面简述开发过程:
1、项目已经正常建立,并有常规的仓储层操作业务逻辑;
2、项目添加h2数据库的引用,打开pom.xml,添加:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
3、修改配置文件,单元测试要使用不同的数据库连接配置,这里通过 spring.profiles 来区分:
注意:为了保证数据库表结构能正常创建,单元测试时ddl-auto要配置为 update,而在生产环境则应该配置为validate。
server:
port: 8801
spring:
application:
name: jpa-unittest
profiles:
active: dev
jpa:
show-sql: false # 这个只会输出在控制台,不会记录到日志里
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
open-in-view: false
--- # 2个三横杠之间表示一个环境配置
spring:
profiles: unittest # 单元测试,通过注解 ActiveProfiles 使用
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
jpa:
hibernate:
ddl-auto: update # 实体与数据库不一致时,自动修改表结构
---
spring:
profiles: dev # 开发使用这一段
datasource:
url: jdbc:mysql://10.2.5.2:3306/firstdemodb?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false
username: beinet
password: beinet.cn
driver-class-name: com.mysql.cj.jdbc.Driver
tomcat:
initSQL: "SET NAMES utf8mb4"
jpa:
hibernate:
ddl-auto: validate # 实体与数据库不一致时,报异常,不应当修改生产数据库,当然也不应该给权限
3、书写你的单元测试代码就可以了,需要注意的是要在单元测试代码里激活unittest配置:
import beinet.cn.demounittestjpa.entity.Aaa;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.util.Assert;
import java.util.List;
@SpringBootTest
@ActiveProfiles("unittest")
class DemoUnittestJpaApplicationTests {
@Autowired
DbController controller;
@Test
void contextLoads() {
List<Aaa> arr = controller.getAll();
Assert.isTrue(arr.isEmpty(), "初始化h2数据库,应该返回空");
Aaa item = controller.update(12, 10);
Assert.isTrue(item.getId() == 1, "12不存在,应该插入成功,且id为1");
Assert.isTrue(item.getNum() == 10, "插入出错?");
好了,到这里,JPA数据库操作的单元测试演示就完成了,你在运行时如果有问题,可以下载上面的源码,进行对比,看看你的代码哪里有问题。