简体   繁体   English

Spring boot - WebFlux - WebTestClient - 将响应转换为 responseEntity

[英]Spring boot - WebFlux - WebTestClient - convert response to responseEntity

I have a Reactive controller which returns:我有一个 Reactive 控制器,它返回:

@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.我正在使用WebTestClient来测试这个端点,但我想提取黄瓜的响应实体以进一步验证。

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:我可以通过执行以下操作来获取 JSON:

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.但是我想看看我是否可以获得整个ResponseEntity以便我可以验证标头、缓存标头和正文。

You will never be able to get a ResponseEntity in your test.您将永远无法在测试中获得ResponseEntity WebTestClient.ResponseSpec returned from exchange() is the only way to check the answer from your Controller.exchange()返回的WebTestClient.ResponseSpec是从控制器检查答案的唯一方法。 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). ResponseEntity只是您在方法中返回的对象,但是一旦 Jackson 对其进行序列化,它就会转换为常规 HTTP 响应(在您的情况下,他的正文中包含 JSON 和常规 HTTP 标头)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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