java 如何为MockMvc独立设置指定日期格式

cld4siwp  于 2023-04-19  发布在  Java
关注(0)|答案(1)|浏览(97)

我有一个这样的端点:

@GetMapping("/path")
public ResponseDTO<Page<Program>> getProgramsByUserId(@PathVariable String userId,
                                                      Pageable pageable,
                                                      @RequestParam(required = false) LocalDate from,
                                                      @RequestParam(required = false) LocalDate to) {

    return null;
}

和Spring的财产

spring:
  mvc:
    format:
      date: iso

为我的请求参数指定日期格式。我有一个测试我的控制器:

@ExtendWith(MockitoExtension.class)
class Test {

    private MockMvc mockMvc;

    @InjectMocks
    private Controller controller;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @BeforeEach
    void setUp() {
        objectMapper.registerModule(new JavaTimeModule());
        mockMvc = MockMvcBuilders
                .standaloneSetup(controller)
                .setControllerAdvice(new GlobalControllerAdvice())
                .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
                .build();
    }

    @Test
    void test() throws Exception {
        //given
        var pageable = PageRequest.of(0, 5);
        var from = LocalDate.of(2022, 1, 1);
        var to = LocalDate.of(2022, 12, 31);

        MvcResult mvcResult = mockMvc.perform(get("/path")
                        .param("page", pageable.getPageNumber() + "")
                        .param("size", pageable.getPageSize() + "")
                        .param("from", from.toString())
                        .param("to", to.toString()))
                .andExpect(status().isOk())
                .andReturn();
    }

}

在这里,我将mockMvc构建为standaloneSetup
问题:当我运行我的测试时,它无法将日期从2022-01-01的字符串转换为LocalDate对象,因为这个测试没有使用Spring属性,而且可能无法使用,因为我使用的是standaloneSetup
问:如何配置我的mockMvc,使其能够将字符串日期转换为LocalDate对象?
注意:我知道,我可以为我的请求参数使用@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)注解,但我想通过spring属性全局地这样做。

dauxcl2d

dauxcl2d1#

这可以通过将WebConversionService添加到mockMvc来完成:

mockMvc = MockMvcBuilders
        .standaloneSetup(controller)
        .setConversionService(
                new WebConversionService(new DateTimeFormatters().dateFormat("iso"))
            )
        .setControllerAdvice(new GlobalControllerAdvice())
        .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
        .build();

时间和日期时间格式可以类似地设置,参考DateTimeFormatters

如何找到?

1.我在库中搜索属性spring.mvc.format.time并查看找到的spring-configuration-metadata.json

{
   "name": "spring.mvc.format.date",
   "type": "java.lang.String",
   "description": "Date format to use, for example 'dd\/MM\/yyyy'.",
   "sourceType": "org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties$Format"
 },

1.然后我检查谁在使用WebMvcProperties$Format#getDate(),它将我引导到WebMvcAutoConfiguration#mvcConversionService

@Bean
 @Override
 public FormattingConversionService mvcConversionService() {
     Format format = this.mvcProperties.getFormat();
     WebConversionService conversionService = new WebConversionService(new DateTimeFormatters()
             .dateFormat(format.getDate()).timeFormat(format.getTime()).dateTimeFormat(format.getDateTime()));
     addFormatters(conversionService);
     return conversionService;
 }

相关问题