Roman Roman - 3 years ago 143
reST (reStructuredText) Question

How to mock Spring WebClient in Unit Test

We wrote a small Spring Boot REST application, which performs a REST request on another REST endpoint.

public class Application
private WebClient webClient;

@RequestMapping(value = "/zyx", method = POST)
XyzApiResponse zyx(@RequestBody XyzApiRequest request, @RequestHeader HttpHeaders headers)
.flatMap(response ->
response.bodyToMono(XyzServiceResponse.class).map(r ->
if (r != null)

if (!response.statusCode().is2xxSuccessful())
throw new ProcessResponseException(
"Bad status response code " + response.statusCode() + "!");

return r;
.subscribe(body ->
// Do various things
}, throwable ->
// This section handles request errors

return XyzApiResponse.OK;

We are new to Spring and are having trouble writing a Unit Test for this small code snippet.

Is there an elegant (reactive) way to mock the webClient itself or to start a mock server that the webClient can use as an endpoint?

Answer Source

I think the build-in spring support for this is still under way -

I really like wiremock to (integration-)test such scenarios. Especially because you test the whole serialization and deserialization with this. With wiremock you start a server that serves your requests using predefined stubs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download