首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring WebTestClient JSON LocalDate解码

Spring WebTestClient JSON LocalDate解码
EN

Stack Overflow用户
提问于 2018-04-13 15:07:25
回答 1查看 707关注 0票数 0

在Spring Boot2.0.1中使用WebTestClient时,我会得到不同格式的日期,这取决于我绑定测试客户端的方式,请参见下面的代码。

那么,如何让WebTestClient.bindToController返回格式化为2018-04-13LocalDate呢?当我调用WebTestClient.bindToServer()时,我得到了预期的格式。

代码语言:javascript
复制
@RestController
public class TodayController {
  @GetMapping("/today")
  public Map<String, Object> fetchToday() {
    return ImmutableMap.of("today", LocalDate.now());
  }
}

测试:

代码语言:javascript
复制
@ExtendWith({SpringExtension.class})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class TodayControllerTest {

  @LocalServerPort
  private int randomPort;

  @Autowired
  private TodayController controller;

  @Test
  void fetchTodayWebTestClientBoundToController() {
     WebTestClient webTestClient = WebTestClient.bindToController(controller)
        .configureClient()
        .build();
    webTestClient.get().uri("/today")
        .exchange()
        .expectBody()
        .json("{\"today\":[2018,4,13]}");
}

@Test
void fetchTodayWebTestClientBoundToServer() {
    WebTestClient webTestClient = WebTestClient.bindToServer()
        .baseUrl("http://localhost:" + randomPort)
        .build();

    webTestClient.get().uri("/today")
        .exchange()
        .expectBody()
        .json("{\"today\":\"2018-04-13\"}");
}
EN

回答 1

Stack Overflow用户

发布于 2018-05-14 07:04:10

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

代码语言:javascript
复制
@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提供了更详细的答案

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49811206

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档