3

假设我们有一个o.s.w.reactive.function.server.ServerResponse.

获取其主体内容的正确方法是什么,换句话说如何实现fetchBodyAsString功能?

test(){
  ServerResponse response = getResponseFromService("mock data");

  String body = fetchBodyAsString(response);

  assertEquals("hello", body);
}

您能否详细说明一下为什么ServerResponse所有东西都有方法(cookies(), headers(), statusCode()),但响应体?我想应该有一种方法来获取身体 writeTo(),虽然它是绝对模糊的如何使用它。

4

3 回答 3

3

为了单元测试的目的,我正在四处寻找类似的东西,并将下面的代码拼接在一起。它在 Kotlin 中,但应该相对容易转换为 Java 并解决您的问题(尽管它确实看起来有点 hacky)。

    fun fetchBodyAsString(serverResponse: ServerResponse): String {
        val DEFAULT_CONTEXT: ServerResponse.Context = object : ServerResponse.Context {
            override fun messageWriters(): List<HttpMessageWriter<*>> {
                return HandlerStrategies.withDefaults().messageWriters()
            }

            override fun viewResolvers(): List<ViewResolver> {
                return Collections.emptyList()
            }
        }

        // Only way I could figure out how to get the ServerResponse body was to have it write to an exchange
        val request = MockServerHttpRequest.get("http://thisdoenstmatter.com").build()
        val exchange = MockServerWebExchange.from(request)
        serverResponse.writeTo(exchange, DEFAULT_CONTEXT).block()
        val response = exchange.response
        return response.bodyAsString.block()!!
    }

基本上需要创建一个假MockServerWebExchange的并对其进行ServerResponse写入以将其翻译成一个MockServerHttpResponse,您可以相当轻松地将响应体拉出。这绝对不是优雅的,但它有效。

另请注意,我没有测试上述函数本身,只是它编译。它应该可以工作,因为函数的内部代码正是我们正在使用的。

至于你的其他问题ServerResponse,我不知道答案,但也很好奇!

于 2020-07-29T23:51:46.847 回答
3

据我所知, ServerResponse用于控制器或路由器功能。对于测试,您可以使用WebTestClient

@Autowired
WebTestClient webTestClient;


@Test
void test() {

    webTestClient.get()
            .exchange()
            .expectStatus()
            .isOk()
            .expectHeader()
            .contentType(MediaType.APPLICATION_JSON)
            .expectBody()
            .jsonPath("data.name").isEqualTo("name");


}

或者

@Autowired
WebTestClient webTestClient;


@Test
void test() {

    FluxExchangeResult<String> result = webTestClient.get()
            .exchange()
            .returnResult(String.class);

    int rawStatusCode = result.getRawStatusCode();
    HttpStatus status = result.getStatus();
    HttpHeaders responseHeaders = result.getResponseHeaders();
    String stringResponseBody = result.getResponseBody().blockFirst();

}
于 2020-03-22T12:21:02.440 回答
1

这基于上面的 Alan Yeung 解决方案,Java 除外。在不加载应用程序上下文的情况下,必须有一种更好的“本机”方式来做到这一点。

public class ServerResponseExtractor {

  public static <T> T serverResponseAsObject(ServerResponse serverResponse,
      ObjectMapper mapper, Class<T> type) {
    String response = serverResponseAsString(serverResponse);
    try {
      return mapper.readValue(response, type);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }
  }

  public static String serverResponseAsString(ServerResponse serverResponse) {
    MockServerWebExchange exchange = MockServerWebExchange.from(
            MockServerHttpRequest.get("/foo/foo"));

    DebugServerContext debugServerContext = new DebugServerContext();
    serverResponse.writeTo(exchange, debugServerContext).block();

    MockServerHttpResponse response = exchange.getResponse();
    return response.getBodyAsString().block();

  }

  private static class DebugServerContext implements ServerResponse.Context {
    @Override
    public List<HttpMessageWriter<?>> messageWriters() {
      return HandlerStrategies.withDefaults().messageWriters();
    }
    @Override
    public List<ViewResolver> viewResolvers() {
      return Collections.emptyList();
    }
  }

}
于 2021-01-25T20:58:49.447 回答