首页 > 解决方案 > 如何在 Spring 测试环境中反序列化 ClientResponse 主体?

问题描述

我正在尝试创建一个ClientResponsein 测试并将其用于测试服务,该服务也使用标准方式进行反序列化response.bodyToMono(..class..)。但似乎我构建虚假客户端响应的方式有问题。因为我接受UnsupportedMediaTypeException了测试。

然而,当 WebClient 返回ClientResponse(内部构建)时,相同的代码在运行时 SpringBoot 应用程序中工作正常。

让我们看一下失败的最简单情况

org.springframework.web.reactive.function.UnsupportedMediaTypeException:
             Content type 'application/json' not supported for bodyType=java.lang.String[]

 void test()
 {
   String body = "[\"a\", \"b\"]";
   ClientResponse response = ClientResponse.create(HttpStatus.OK)
                                           .header(HttpHeaders.CONTENT_TYPE, 
                                                   MediaType.APPLICATION_JSON_VALUE)
                                           .body(body)
                                           .build();

   String[] array = response.bodyToMono(String[].class).block();

   assertEquals(2, array.length);
}

请帮助我理解,应该如何构建客户端响应以允许在测试环境中进行标准(json -> 对象)反序列化。

标签: javaspringtestingspring-webflux

解决方案


手动创建的ClientResponse无权访问Jackson2Json默认列表中的交易策略。可能它可以使用 Spring 自动配置进行配置,在没有 Spring 上下文的测试中将其关闭。

这是强制(反)序列化 String <-> json 的直接方法:

static ExchangeStrategies jacksonStrategies()
{
    return ExchangeStrategies
            .builder()
            .codecs(clientDefaultCodecsConfigurer ->
            {
                clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(new ObjectMapper(), MediaType.APPLICATION_JSON));
                clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(new ObjectMapper(), MediaType.APPLICATION_JSON));

            }).build();
}

然后在create函数中使用

ClientResponse.create(HttpStatus.OK, jacksonStrategies())...

推荐阅读