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

使用 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 中的逻辑被执行。

正确的单元测试方法

正确的做法是使用 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,可以避免一些潜在的错误。

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享