Spring Boot Test 系列3 - 使用WebTestClient测试Web层

本文介绍了Spring Boot Test系列的第三篇,重点是使用WebTestClient测试Web层。相较于TestRestTemplate和MockMvc,WebTestClient提供异步、非阻塞式测试,并支持流式断言,提高了测试效率。文中通过示例代码展示了如何引入spring-boot-starter-webflux依赖,以及如何使用WebTestClient替换TestRestTemplate和MockMvc。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Boot Test 系列3 - 使用WebTestClient测试Web层

前言

本文为Spring Boot Test系列的第三篇的使用WebTestClient测试Web层。

前置文章:

使用WebTestClient测试Web层

Spring Boot Test 系列2 - 测试Web层 中说明了如何通过TestRestTemplateMockMvc 来调用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

WebTestClientTestRestTemplate 分别是WebClientRestTempalte的测试工具类。

WebClientRestTempalte的比较:

  • RestTemplate - 同步,阻塞式,Spring Web框架的一部分,支持经典的request/response架构
  • WebClient - 异步,非阻塞式,Spring Reactive框架的一部分,支持Event Driven架构

类路径和包名如下:

org.springframework.boot.test.web.client.TestRestTemplate # spring-boot-test
org.springframework.web.client.RestTemplate # spring-web

org.springframework.test.web.reactive.server.WebTestClient # spring-test
org.springframework.web.reactive.function.client.WebClient # spring-webflux

示例代码:

import org.junit.jupiter.api.DisplayName;
import 
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值