gpt4 book ai didi

java - Spring WebTestClient JSON LocalDate 解码

转载 作者:行者123 更新时间:2023-12-02 11:22:42 25 4
gpt4 key购买 nike

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

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

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

测试:

@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\"}");
}

最佳答案

事实证明,在使用 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 的更详细回答

关于java - Spring WebTestClient JSON LocalDate 解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49811206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com