Member-only story

Retry WebClient Request

Retrying a WebClient request using RetrySpec, and unit-testing it

Gerald Nguyen
4 min readDec 30, 2022

Problem Statement

Sometimes web request fails, for whatever reason, and you need to retry it

Let’s simulate a failed request scenario in a unit test. In the below code, the webClient attempts to submit a GET request to /employee/100 (stored in constant PATH). We mocked the backend server to fail with common status codes such as BAD_REQUEST, UNAUTHORIZED and validate that the client throws WebClientResponseException upon receiving such statuses.

@ParameterizedTest
@EnumSource(value = HttpStatus.class, mode = EnumSource.Mode.INCLUDE, names = {
"BAD_REQUEST", "UNAUTHORIZED", "FORBIDDEN",
"SERVICE_UNAVAILABLE", "INTERNAL_SERVER_ERROR"
})
void throwExceptionWhenReceiveNon200Response(HttpStatus status) throws InterruptedException {
// request
var webClient = WebClient.builder().baseUrl(baseUrl).build();
var request = webClient.get()
.uri(PATH)
.retrieve()
.bodyToMono(String.class);

// response to first request with fail status
mockBackEnd.enqueue(new MockResponse().setResponseCode(status.value()));

// assert that exception thrown due to non-200 response
var ex = assertThrows(WebClientResponseException.class, () -> request.block());
assertEquals(status, ex.getStatusCode());

// extra assert that the path is correct
assertEquals(PATH, mockBackEnd.takeRequest().getPath());
}

--

--

Gerald Nguyen
Gerald Nguyen

Written by Gerald Nguyen

Engineering Lead. I write about software development, and sometimes writing itself. Mostly original. https://bit.ly/geraldnguyen

Responses (2)