在Spring Boot2.0.1中使用WebTestClient时,我会得到不同格式的日期,这取决于我绑定测试客户端的方式,请参见下面的代码。
那么,如何让WebTestClient.bindToController返回格式化为2018-04-13的LocalDate呢?当我调用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\"}");
}发布于 2018-05-14 07:04:10
事实证明,在使用WebTestClient.bindToController时,我需要设置杰克逊解码器/编码器。例如:
@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提供了更详细的答案
https://stackoverflow.com/questions/49811206
复制相似问题