文章目录
Spring Boot Test 系列3 - 使用WebTestClient测试Web层
前言
本文为Spring Boot Test系列的第三篇的使用WebTestClient测试Web层。
前置文章:
使用WebTestClient测试Web层
在Spring Boot Test 系列2 - 测试Web层 中说明了如何通过TestRestTemplate
和MockMvc
来调用API。本文描述另外一种调用API方法,即通过WebTestClient
来调用API来测试Web层。
引入spring-boot-starter-webflux依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<scope>test</scope>
</dependency>
本文中只在测试类中使用了WebTestClient
,因此将scope设置为test
即可。
如果不引入spring-boot-starter-webflux
会出现webTestClient bean无法注入的问题。
使用WebTestClient代替TestRestTemplate
WebTestClient
和TestRestTemplate
分别是WebClient
和RestTempalte
的测试工具类。
WebClient
和RestTempalte
的比较:
RestTemplate
- 同步,阻塞式,Spring Web框架的一部分,支持经典的request/response架构WebClien
t - 异步,非阻塞式,Spring Reactive框架的一部分,支持Event Driven架构
类路径和包名如下:
org.springframework.boot.test.web.client.TestRestTemplate # spring-boot-test
org.springframework.web.client.RestTemplate