简体   繁体   中英

Spring boot - WebFlux - WebTestClient - convert response to responseEntity

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM