Spring WebTestClient JSON LocalDate解码

时间:2018-04-13 07:07:25

标签: java spring-boot junit5 spring-boot-test

在Spring Boot 2.0.1中使用WebTestClient时,我会根据绑定测试客户端的方式获得不同的格式化日期,请参阅下面的代码。

那么如何让WebTestClient.bindToController返回格式为LocalDate的{​​{1}}?当我致电2018-04-13时,我得到预期的格式。

WebTestClient.bindToServer()

试验:

@RestController
public class TodayController {
  @GetMapping("/today")
  public Map<String, Object> fetchToday() {
    return ImmutableMap.of("today", LocalDate.now());
  }
}

1 个答案:

答案 0 :(得分:1)

事实证明,我需要在使用WebTestClient.bindToController时设置Jackson解码器/编码器。例如

@Test
  public void fetchTodayWebTestClientBoundToController() {
     WebTestClient webTestClient = WebTestClient.bindToController(controller)
         .httpMessageCodecs((configurer) -> {
             CodecConfigurer.DefaultCodecs defaults = configurer.defaultCodecs();
             defaults.jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper, new MimeType[0]));
             defaults.jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper, new MimeType[0]));
         })
        .configureClient()
        .build();
    webTestClient.get().uri("/today")
        .exchange()
        .expectBody()
        .json("{\"today\":\"2018-04-30\"}");
  }

来自Spring boot project

的更详细答案