Spring boot - WebFlux - WebTestClient - convert response to responseEntity

1.9k Views Asked by At

I have a Reactive controller which returns:

@ResponseBody
@GetMapping("/data")
public Mono<ResponseEntity<Data>> getData() {
  //service call which returns Mono<Data> dataMono
  Mono<ResponseEntity<Data>> responseEntityMono = dataMono
          .map(data -> ResponseEntity.ok(data))
          .doFinally(signalType -> {});

  return responseEntityMono;
}

I am using WebTestClient to test this endpoint, but I want to extract the response entity for cucumber to validate further.

I tried this:

@Autowired private WebTestClient webTestClient;

public ResponseEntity get() {
  EntityExchangeResult < ResponseEntity > response = webTestClient.get()
    .uri(uriBuilder ->
      uriBuilder
      .path(VISUALIZATION_URL)
      .build())
    .header("Accepts", "application/json")
    .exchange()
    .expectStatus().isOk()
    .expectHeader().contentType(MediaType.APPLICATION_JSON_VALUE)
    .expectBody(ResponseEntity.class)
    .returnResult();
  return response.getResponseBody();
}

but I am getting an error. I can get the JSON by doing:

public String get() {
  BodyContentSpec bodyContentSpec = webTestClient.get()
    .uri(uriBuilder ->
      uriBuilder
      .path(URL)
      .build())
    .header("Accepts", "application/json")
    .exchange()
    .expectStatus().isOk()
    .expectHeader().contentType(MediaType.APPLICATION_JSON_VALUE)
    .expectBody();
  return new String(bodyContentSpec.returnResult().getResponseBody());
}

But I am trying to see if I can get the whole ResponseEntity so that I can validate headers, caching headers, and body.

1

There are 1 best solutions below

0
On

You will never be able to get a ResponseEntity in your test. WebTestClient.ResponseSpec returned from exchange() is the only way to check the answer from your Controller. ResponseEntity is just the object you return in your method but once Jackson serializes it, it is converted to a regular HTTP response (in your case with JSON in his body and regular HTTP headers).