【问题标题】:Spring WebTestClient JSON LocalDate decodeSpring WebTestClient JSON LocalDate 解码
【发布时间】:2018-04-13 07:07:24
【问题描述】:

在 Spring Boot 2.0.1 中使用 WebTestClient 时,我得到不同的格式化日期,具体取决于我绑定测试客户端的方式,请参见下面的代码。

那么我怎样才能让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\"}");
}

【问题讨论】:

  • 当我在 start.spring.io 上生成的项目上进行测试时,两个测试都是绿色的。如果您复制它,您能否仔细检查并分享一个复制项目?
  • 它们都是绿色的,但预期的日期格式不同,期望它们今天都返回,格式为 2018-04-13

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


【解决方案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的更详细回答

【讨论】:

  • 如果使用bindToController 不是硬性要求,您也可以自动连接WebTestClient
猜你喜欢
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-27
  • 2019-01-08
  • 2020-10-24
相关资源
最近更新 更多