如何测试Spring WebClient何时重试?



我需要实现以下行为:

  • 发出 REST 发布请求
  • 如果响应返回状态429 Too many requests,则重试最多 3 次,延迟 1 秒
  • 如果第三次重试失败或发生任何其他错误,请记录并向数据库写入某些内容
  • 如果请求成功(http 状态 200(,请记录一些信息

我想使用Spring WebClient来实现这个目的,并想出了这个代码:

Mono<ClientResponse> response = webClient.post()
.uri(URI.create("/myuri"))
.body(BodyInserters.fromObject(request))
.retrieve()
.onStatus(httpStatus -> httpStatus.equals(HttpStatus.TOO_MANY_REQUESTS), 
response -> Mono.error(new TooManyRequestsException("System is overloaded")))
.bodyToMono(ClientResponse.class)
.retryWhen(Retry.anyOf(TooManyRequestsException.class)
.fixedBackoff(Duration.ofSeconds(1)).retryMax(3))
.doOnError(throwable -> saveToDB(some_id, throwable))
.subscribe(response -> logResponse(some_id, response));

现在我想测试重试机制和错误处理是否按预期工作。也许我可以为此目的使用 StepVerifier,但我只是无法弄清楚如何在我的情况下使用它。有什么有用的提示吗?

我认为你可以用模拟Web服务器(例如MockWebServer(来测试它。

@Test
public void testReactiveWebClient() throws IOException
{
MockWebServer mockWebServer = new MockWebServer();
String expectedResponse = "expect that it works";
mockWebServer.enqueue(new MockResponse().setResponseCode(429));
mockWebServer.enqueue(new MockResponse().setResponseCode(429));
mockWebServer.enqueue(new MockResponse().setResponseCode(429));
mockWebServer.enqueue(new MockResponse().setResponseCode(200)
.setBody(expectedResponse));
mockWebServer.start();
HttpUrl url = mockWebServer.url("/mvuri");
WebClient webClient = WebClient.create();
Mono<String> responseMono = webClient.post()
.uri(url.uri())
.body(BodyInserters.fromObject("myRequest"))
.retrieve()
.onStatus(
httpStatus -> httpStatus.equals(HttpStatus.TOO_MANY_REQUESTS),
response -> Mono.error(new TestStuff.TooManyRequestsException("System is overloaded")))
.bodyToMono(String.class)
.retryWhen(Retry.anyOf(TestStuff.TooManyRequestsException.class)
.fixedBackoff(Duration.ofSeconds(1)).retryMax(3));
StepVerifier.create(responseMono)
.expectNext(expectedResponse)
.expectComplete().verify();
mockWebServer.shutdown();
}

如果您使用状态代码429将另一个MockResponse排队,则验证将失败,例如错误代码500

Dominik Sandjaja的回答基本上帮助我设置了测试。为了完整起见,我在这里发布了工作版本:

@Test
public void mytest() {
MockResponse mockResponse = new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.setResponseCode(429).setBody("Too many requests");
mockWebServer.enqueue(mockResponse);
mockWebServer.enqueue(mockResponse);
mockWebServer.enqueue(mockResponse);
mockWebServer.enqueue(mockResponse);
Mono<MyClass> responseMono = methodDoingTheAsyncCall.sendAsync(...);
StepVerifier.create(responseMono)
.expectError(RetryExhaustedException.class)
.verify();
}

最新更新