title: How to test Spring WebClient retry when?
body: <p>I need to implement following behavior:</p>
  
  <ul>
  <li>Make a REST post request</li>
  <li>If response returns with a status <code>429 Too many requests</code>, retry up to 3 times with a delay of 1 second</li>
  <li>If the third retry fails or any other error occurs, log and write something to the database</li>
  <li>If the request was successful (http status 200), log some information</li>
  </ul>
  
  <p>I would like to use Spring WebClient for this purpose and came up with this code:</p>
  
  <pre><code>Mono&lt;ClientResponse&gt; response = webClient.post()
              .uri(URI.create("/myuri"))
              .body(BodyInserters.fromObject(request))
              .retrieve()
              .onStatus(httpStatus -&gt; httpStatus.equals(HttpStatus.TOO_MANY_REQUESTS), 
                        response -&gt; Mono.error(new TooManyRequestsException("System is overloaded")))
              .bodyToMono(ClientResponse.class)
              .retryWhen(Retry.anyOf(TooManyRequestsException.class)
                                            .fixedBackoff(Duration.ofSeconds(1)).retryMax(3))
              .doOnError(throwable -&gt; saveToDB(some_id, throwable))
              .subscribe(response -&gt; logResponse(some_id, response));
  </code></pre>
  
  <p>Now I would like to test if the retry mechanism and error handling works as I expect. May be I could use <a href="https://projectreactor.io/docs/test/release/api/reactor/test/StepVerifier.html" rel="noreferrer">StepVerifier</a> for this purpose, but I just cannot figure out how to use it in my case. Any useful hints?</p>