Using MockServerHttpResponse to test WebFilter

Viewed 177

I have a org.springframework.web.server.WebFilter that I am testing. I am mocking the ServerWebExchange to return a MockServerHttpResponse. When the web filter wants to return an error response it uses

    private static Mono<Void> setErrorResponse(ServerWebExchange exchange, String message) {
    ServerHttpResponse response = exchange.getResponse()
    response.statusCode = HttpStatus.BAD_REQUEST
    response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
    DataBuffer buffer = response.bufferFactory().wrap(message.getBytes("UTF-8"))
    return response.writeWith(Flux.just(buffer))
}

Then I try to get the the response body by calling

response.getBodyAsString().block()

But I always get

java.lang.IllegalStateException: No content was written nor was setComplete() called on this response.

How do you use the mock to get the response body that does not seem to get set when using writeWith()?

0 Answers
Related