0

0

使用 Mono.error 进行 WebClient 异常处理的单元测试

心靈之曲

心靈之曲

发布时间:2025-08-17 19:48:02

|

471人浏览过

|

来源于php中文网

原创

使用 mono.error 进行 webclient 异常处理的单元测试

在使用 WebClient 进行异步 HTTP 请求时,doOnError 方法用于处理请求过程中可能发生的异常。为了保证代码的健壮性,我们需要对 doOnError 中的逻辑进行单元测试。一个常见的错误是在单元测试中直接 thenThrow 一个异常,这可能导致 doOnError 无法被触发,从而无法验证异常处理的正确性。

问题描述

假设我们有以下代码,使用 WebClient 发送请求,并在 doOnError 中处理 WebClientResponseException:

public String getResponse(String requestBody) {
    WebClient client = WebClient.create(); // 简化,实际应从外部注入
    String resp = client.post()
            .uri("https://example.com/api")
            .body(BodyInserters.fromValue(requestBody))
            .retrieve()
            .bodyToMono(String.class)
            .doOnError(
                WebClientResponseException.class,
                err -> {
                  // do something, 例如将 WebClientResponseException 转换为自定义异常
                  throw new InvalidRequestException(err.getResponseBodyAsString());
                })
            .block();
    return resp;
}

我们希望编写单元测试来验证当 WebClient 返回错误时,doOnError 中的 InvalidRequestException 能够被正确抛出。

错误的单元测试示例

以下是一个可能错误的单元测试示例:

@Test
void testGetResponse_Error() {
    WebClient webClientMock = Mockito.mock(WebClient.class);
    WebClient.RequestBodyUriSpec requestBodyUriMock = Mockito.mock(WebClient.RequestBodyUriSpec.class);
    WebClient.RequestHeadersSpec requestHeadersMock = Mockito.mock(WebClient.RequestHeadersSpec.class);
    WebClient.ResponseSpec responseMock = Mockito.mock(WebClient.ResponseSpec.class);

    String requestBody = "test request";
    String expectedMessage = "Bad Request Body";
    int expectedCode = 400;
    WebClientResponseException thrownException = new WebClientResponseException(expectedCode, "Bad Request", null, expectedMessage.getBytes(), null);

    Mockito.when(webClientMock.post()).thenReturn(requestBodyUriMock);
    Mockito.when(requestBodyUriMock.uri(Mockito.anyString())).thenReturn(requestBodyUriMock); // 增加 uri 的 mock
    Mockito.when(requestBodyUriMock.body(Mockito.any())).thenReturn(requestHeadersMock);
    Mockito.when(requestHeadersMock.retrieve()).thenReturn(responseMock);
    // 错误的做法:直接 thenThrow 异常
    Mockito.when(responseMock.bodyToMono(String.class)).thenThrow(thrownException);

    SomeService someServiceSpy = new SomeService(webClientMock); // 假设 SomeService 包含 getResponse 方法

    try {
        someServiceSpy.getResponse(requestBody);
        fail("Expected InvalidRequestException to be thrown");
    } catch (InvalidRequestException e) {
        assertEquals(expectedCode, e.getRawStatusCode());
        assertEquals(expectedMessage, e.getMessage());
    }
}

在这个测试中,我们使用 thenThrow 直接抛出 WebClientResponseException。然而,这并不能保证 doOnError 中的逻辑被执行。

知元AI
知元AI

AI智能语音聊天 对讲问答 AI绘画 AI写作 AI创作助手工具

下载

正确的单元测试方法

正确的做法是使用 Mono.error 来模拟 WebClient 抛出的异常。Mono.error 会创建一个包含错误信息的 Mono,当订阅者尝试获取 Mono 中的数据时,错误会被传播,从而触发 doOnError。

以下是修改后的单元测试:

@Test
void testGetResponse_Error() {
    WebClient webClientMock = Mockito.mock(WebClient.class);
    WebClient.RequestBodyUriSpec requestBodyUriMock = Mockito.mock(WebClient.RequestBodyUriSpec.class);
    WebClient.RequestHeadersSpec requestHeadersMock = Mockito.mock(WebClient.RequestHeadersSpec.class);
    WebClient.ResponseSpec responseMock = Mockito.mock(WebClient.ResponseSpec.class);

    String requestBody = "test request";
    String expectedMessage = "Bad Request Body";
    int expectedCode = 400;
    WebClientResponseException thrownException = new WebClientResponseException(expectedCode, "Bad Request", null, expectedMessage.getBytes(), null);

    Mockito.when(webClientMock.post()).thenReturn(requestBodyUriMock);
    Mockito.when(requestBodyUriMock.uri(Mockito.anyString())).thenReturn(requestBodyUriMock); // 增加 uri 的 mock
    Mockito.when(requestBodyUriMock.body(Mockito.any())).thenReturn(requestHeadersMock);
    Mockito.when(requestHeadersMock.retrieve()).thenReturn(responseMock);
    // 正确的做法:使用 Mono.error 模拟异常
    Mockito.when(responseMock.bodyToMono(String.class)).thenReturn(Mono.error(thrownException));

    SomeService someServiceSpy = new SomeService(webClientMock); // 假设 SomeService 包含 getResponse 方法

    try {
        someServiceSpy.getResponse(requestBody);
        fail("Expected InvalidRequestException to be thrown");
    } catch (InvalidRequestException e) {
        assertEquals(expectedCode, e.getRawStatusCode());
        assertEquals(expectedMessage, e.getMessage());
    }
}

通过使用 Mono.error(thrownException),我们确保了当 bodyToMono 尝试获取数据时,thrownException 会被传播,从而触发 doOnError 中的异常处理逻辑。

总结

在对使用 WebClient 的 doOnError 方法进行单元测试时,务必使用 Mono.error 来模拟异常,以确保 doOnError 中的逻辑能够被正确执行。这可以有效地验证异常处理的正确性,提高代码的健壮性。此外,确保 mock 的完整性,例如 uri 的 mock,可以避免一些潜在的错误。

相关专题

更多
scripterror怎么解决
scripterror怎么解决

scripterror的解决办法有检查语法、文件路径、检查网络连接、浏览器兼容性、使用try-catch语句、使用开发者工具进行调试、更新浏览器和JavaScript库或寻求专业帮助等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

188

2023.10.18

500error怎么解决
500error怎么解决

500error的解决办法有检查服务器日志、检查代码、检查服务器配置、更新软件版本、重新启动服务、调试代码和寻求帮助等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

288

2023.10.25

http500解决方法
http500解决方法

http500解决方法有检查服务器日志、检查代码错误、检查服务器配置、检查文件和目录权限、检查资源不足、更新软件版本、重启服务器或寻求专业帮助等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

378

2023.11.09

http请求415错误怎么解决
http请求415错误怎么解决

解决方法:1、检查请求头中的Content-Type;2、检查请求体中的数据格式;3、使用适当的编码格式;4、使用适当的请求方法;5、检查服务器端的支持情况。更多http请求415错误怎么解决的相关内容,可以阅读下面的文章。

413

2023.11.14

HTTP 503错误解决方法
HTTP 503错误解决方法

HTTP 503错误表示服务器暂时无法处理请求。想了解更多http错误代码的相关内容,可以阅读本专题下面的文章。

2026

2024.03.12

http与https有哪些区别
http与https有哪些区别

http与https的区别:1、协议安全性;2、连接方式;3、证书管理;4、连接状态;5、端口号;6、资源消耗;7、兼容性。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

2021

2024.08.16

html编辑相关教程合集
html编辑相关教程合集

本专题整合了html编辑相关教程合集,阅读专题下面的文章了解更多详细内容。

38

2026.01.21

三角洲入口地址合集
三角洲入口地址合集

本专题整合了三角洲入口地址合集,阅读专题下面的文章了解更多详细内容。

19

2026.01.21

AO3中文版入口地址大全
AO3中文版入口地址大全

本专题整合了AO3中文版入口地址大全,阅读专题下面的的文章了解更多详细内容。

255

2026.01.21

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
10分钟--Midjourney创作自己的漫画
10分钟--Midjourney创作自己的漫画

共1课时 | 0.1万人学习

Midjourney 关键词系列整合
Midjourney 关键词系列整合

共13课时 | 0.9万人学习

AI绘画教程
AI绘画教程

共2课时 | 0.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号