欢迎访问我的GitHub
https://github.com/zq2599/blog_demos
内容:所有原创文章分类和汇总,及配套源码,涉及Java、Docker、Kubernetes、DevOPS等;
关于《SpringBoot单元测试》系列
《SpringBoot单元测试》系列旨在通过一系列知识归纳和实战,和读者们一起提升在SpringBoot环境下的单元测试的技能;
本篇概览
本文是《SpringBoot单元测试》系列的第一篇,咱们一起来写几个最简单的单元测试类,了解如何测试Service层和Controller层,包括以下内容:
- 版本和环境信息
- 创建《SpringBoot单元测试》系列所有源码的父工程junitpractice
- 创建本文实战用到的子工程simplebean
- 借助IDEA,对指定java类生成单元测试代码
- 测试SpringBoot项目的Service层
- 测试SpringBoot项目的Controller层,此时模拟web环境,并未启动web server
- 测试SpringBoot项目的Controller层,真正启动web server,用WebTestClient实例发送请求,此时pom.xml中要添加webflux的依赖
- 测试SpringBoot项目的Controller层,真正启动web server,用TestRestTemplate实例发送请求
- 可见上述内容都是些最基本的操作,有助于咱们快速掌握如何编写单元测试用例;
版本和环境信息
整个系列的编码和执行在以下环境进行,供您参考:
- 硬件配置:处理器i5-8400,内存32G,硬盘128G SSD + 500G HDD
- 操作系统:Windows10家庭中文版
- IDEA:2020.2.2 (Ultimate Edition)
- JDK:1.8.0_181
- SpringBoot:2.3.4.RELEASE
- JUnit Jupiter:5.6.2
- 接下来开始实战,咱们先建好SpringBoot项目;
关于lombok
为了简化代码,项目中使用了lombok,请您在IDEA中安装lombok插件;
源码下载
如果您不想编码,可以在GitHub下载所有源码,地址和链接信息如下表所示(
https://github.com/zq2599/blog_demos):
- 这个git项目中有多个文件夹,本章的应用在junitpractice文件夹下,如下图红框所示:
- junitpractice是父子结构的工程,本篇的代码在simplebean子工程中,如下图:
创建Maven父工程
- 为了便于管理整个系列的源码,在此建立名为junitpractice的maven工程,后续所有实战的源码都作为junitpractice的子工程;
- junitpractice的pom.xml如下,可见是以SpringBoot的2.3.4.RELEASE版本作为其父工程:
4.0.0
simplebean
org.springframework.boot
spring-boot-starter-parent
2.3.4.RELEASE
com.bolingcavalry
junitpractice
1.0-SNAPSHOT
pom
UTF-8
UTF-8
1.8
org.projectlombok
lombok
1.16.16
本篇的源码工程
- 创建名为simplebean的子工程,pom.xml如下,注意单元测试要依赖spring-boot-starter-test:
4.0.0
com.bolingcavalry
junitpractice
1.0-SNAPSHOT
../pom.xml
com.bolingcavalry
simplebean
0.0.1-SNAPSHOT
simplebean
Demo project for simplebean in Spring Boot junit
1.8
org.springframework.boot
spring-boot-starter-web
org.projectlombok
lombok
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-webflux
test
org.springframework.boot
spring-boot-maven-plugin
- 接下来写一些最简单的代码,让服务能运行起来,service接口:
package com.bolingcavalry.simplebean.service;
public interface HelloService {
String hello(String name);
}
- 接口实现:
package com.bolingcavalry.simplebean.service.impl;
import com.bolingcavalry.simplebean.service.HelloService;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
@Service()
public class HelloServiceImpl implements HelloService {
@Override
public String hello(String name) {
return "Hello " + name;
}
}
- controller类,调用了HelloService 的服务:
package com.bolingcavalry.simplebean.controller;
import com.bolingcavalry.simplebean.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public String logExtend(@PathVariable String name){
return helloService.hello(name);
}
}
- 准备工作完成,可以编写单元测试的代码了;
用IEDA生成单元测试代码
- 打开HelloServiceImpl.java,如下操作:
- 在弹出的菜单中选择Test,如下图:
- 如下图,把红框中的hello方法勾选上:
- 此时,IDEA会帮我们自动生成单元测试代码,内容和位置如下图所示:
- 如下图操作,即可执行新增的单元测试代码HelloServiceImplTest.java:
- 以上就是通过IDEA生成单元测试代码的过程,接下来咱们修改HelloServiceImplTest.java的代码,对SpringBoot工程进行测试;
测试Service层
- 先来测试工程的Service层,看看HelloService能否正常工作,修改HelloServiceImplTest.java,修改后如下:
@SpringBootTest
class HelloServiceImplTest {
private static final String NAME = "Tom";
@Test
void hello(@Autowired HelloService helloService) {
TestCase.assertEquals("Hello " + NAME, helloService.hello(NAME));
}
}
- 上述代码要注意的是两个注解,第一是SpringBootTest,用于开启springboot对junit的支持(例如指定SpringExtension作为ParameterResolver),第二个是hello方法的入参,通过Autowired取得了Spring容器中的HelloService实例;
- TestCase.assertEquals方法有两个入参,如果它们的equals比较结果为true,则表示测试通过;
- 鼠标点击下图红框位置:
- 在弹出的菜单中,点击Run ‘HelloServiceImplTest’,如下图红框所示:
- 执行结果如下图所示,测试通过:
- 新增方法testApplicationContext,用来验证单元测试时能否使用Spring的ApplicationContext实例:
@Test
void testApplicationContext(@Autowired ApplicationContext applicationContext) {
// 通过applicationContext从spring环境取得helloService实例
HelloService helloService = applicationContext.getBean(HelloService.class);
// 非空
TestCase.assertNotNull(helloService);
// 相等
TestCase.assertEquals("Hello " + NAME, helloService.hello(NAME));
}
- 如下图,可见单元测试时可以使用Spring的ApplicationContext实例来执行spring相关的操作:
- 对service层进行单元测试的基本操作就完成了,接下来尝试web接口的测试;
测试Controller层(未启动web server)
- 除了service层,Controller层提供的web接口也是单元测试的重点,接下来尝试最简单的Controller层单元测试;
- 新建HelloControllerTest.java,内容如下:
package com.bolingcavalry.simplebean.service.impl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
private static final String NAME = "Tom";
@Test
void hello(@Autowired MockMvc mvc) throws Exception {
// 模拟
mvc.perform(get("/" + NAME))
.andExpect(status().isOk())
.andExpect(content().string("Hello " + NAME));
}
}
- 上述代码中,通过AutoConfigureMockMvc注解开启MockMvc的自动装配,再通过MockMvc模拟web环境,在不启动web server的情况下调用到Controller层的服务,再用两个andExpect方法分别验证web服务的返回码和返回内容;
- 测试通过如下图:
测试Controller层(启动web server)
通过MockMvc的方式调用Controller层的服务时,并没有启动web server,如果我们希望单元测试时web server就像生产环境一样是正常运行的,就不要用MockMvc来模拟web环境,来看看如何在单元测试时将web server启动;
- SpringBootTest的注解有个属性webEnvironment,其值有以下四种:
MOCK : 模拟的web服务环境,这是默认取值,刚才的HelloControllerTest.java就是这种
RANDOM_PORT : 启动web server,服务端口随机取值
DEFINED_PORT : 启动web server, 服务端口是当前项目设置的端口
NONE : 不提供web服务环境
- 根据上述定义,新建单元测试类HelloControllerWithWebTestClientTest.java,webEnvironment取值为RANDOM_PORT,这样就能把嵌入式tomcat启动了:
package com.bolingcavalry.simplebean.service.impl;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.web.reactive.server.WebTestClient;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
public class HelloControllerWithWebTestClientTest {
private static final String NAME = "Tom";
@Test
void hello(@Autowired WebTestClient webClient, @LocalServerPort int port) throws Exception {
webClient
.get()
.uri("/" + NAME)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("Hello " + NAME);
log.info("web端口是[{}]", port);
}
}
- 从上述代码可见,发起请求用的是WebTestClient实例,即从客户端发请求到web server,来验证Controller层的服务;
- 使用LocalServerPort注解,可以得到服务端口的数值;
- 使用WebTestClient实例时,pom.xml中一定要添加webflux的依赖,如下:
org.springframework.boot
spring-boot-starter-webflux
test
- 单元测试执行结果如下,红框1证实了嵌入式tomcat已经被启动,红框2就是web监听的端口:
另一种访问web server的方式
- 刚刚咱们使用WebTestClient来访问web server,但使用WebTestClient必须要在pom.xml中添加webflux的依赖,这个略微有些麻烦,其实您还可以选择TestRestTemplate来取代WebTestClient,而使用TestRestTemplate时无需额外的jar依赖;
- 新建HelloControllerWithTestRestTemplateTest.java,这里面使用TestRestTemplate实例向web server发送请求,另外还展示了assertThat的用法:
package com.bolingcavalry.simplebean.service.impl;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
public class HelloControllerWithTestRestTemplateTest {
private static final String NAME = "Tom";
@Test
void hello(@Autowired TestRestTemplate testRestTemplate, @LocalServerPort int port) throws Exception {
log.info("web端口是[{}]", port);
// 向web server发送请求
ResponseEntity responseEntity = testRestTemplate.exchange("/" + NAME, HttpMethod.GET, HttpEntity.EMPTY, String.class);
// 检查code
assertThat(responseEntity.getStatusCode()).isEqualByComparingTo(HttpStatus.OK);
// 检查内容
assertThat(responseEntity.getBody()).isEqualTo("Hello " + NAME);
}
}
- 执行单元测试成功:
- 至此,咱们通过四个简单示例熟悉了最基本的SpringBoot单元测试,接下来的章节会展开更多知识点和细节,对单元测试做更深入的学习