How to log the returned body in WebClient in unit testing?
Method 1:
The simplest way is just printing out the request and response below:
wireMockServer.addMockServiceRequestListener(( Request request, Response response) -> {
System.out.println("Request was: " + request);
System.out.println("Response was: " + response);
});
Method 2:
To log the returned body in your Spring Boot application, you can use the logging capabilities of Spring’s WebClient
. Here's how you can modify your WebClient
instance to log the returned body:
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import reactor.core.publisher.Mono;
// ...
WebClient webClient = WebClient.builder()
.baseUrl(wireMockServer.baseUrl())
.filter(logRequest())
.filter(logResponse())
.build();
// ...
private ExchangeFilterFunction logRequest() {
return (clientRequest, next) -> {
log.info("Request: {} {}", clientRequest.method(), clientRequest.url());
clientRequest.headers().forEach((name, values) -> values.forEach(value -> log.info("{}={}", name, value)));
return next.exchange(clientRequest);
};
}
private ExchangeFilterFunction logResponse() {
return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
log.info("Response: {}", clientResponse.statusCode());
clientResponse.headers().asHttpHeaders().forEach((name, values) -> values.forEach(value -> log.info("{}={}", name, value)));
return Mono.just(clientResponse);
});
}
In this code, logRequest()
and logResponse()
are ExchangeFilterFunctions
that log the request and response details respectively. They are added to the WebClient
via the filter()
method.
Please note that this will only log the status and headers of the response. Logging the body of the response is more complex because the body is a stream that can only be read once. If you read the body for logging, it won’t be available for further processing. If you need to log the body, you might need to buffer the body so it can be read twice, but this can increase memory usage and complexity.
You may get an error saying “Cannot resolve symbol ‘log’”. In this case you should need to add a slf4j logger to your class. For example:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class YourSampleTest{
private static final Logger log = LoggerFactory.getLogger(TestBestandsServiceProxy.class);
// rest of your code
}