java - 如何在 Spring 测试环境中反序列化 ClientResponse 主体?
问题描述
我正在尝试创建一个ClientResponse
in 测试并将其用于测试服务,该服务也使用标准方式进行反序列化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 -> 对象)反序列化。
解决方案
手动创建的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())...
推荐阅读
- perl - perl 检查目录中是否存在与特定模式匹配的文件名
- python - 使用动作属性时没有得到描述
- javascript - 如果在 html 表格中未选中复选框,如何隐藏一行?
- c# - 字符串参数应该只允许在.net c#中的Web api路由属性正则表达式中使用字母数字和点
- git - Git:成功将master与3.0版合并后master仍然没有得到所有更新
- java - 在 Android 的 Arraylist 中从 Firebase 检索数据
- indexing - RavenDB - 何时使用 AbstractIndexCreationTask 索引、排序和存储方法?
- css - Bootstrap 4 创建非模态对话框
- html - 奇怪的交互 ng-hide 和 data-charts angular js
- mysql - 使用 Doctrine ind Akeneo 查询产品