首页 > 解决方案 > Spring MVC 自定义格式化程序在测试中工作但在浏览器中失败

问题描述

我有一个控制器:(根据Spring WebMVC @ModelAttribute 参数样式

@GetMapping("/time/{date}")
@ResponseStatus(OK)
public LocalDate getDate(
        @ModelAttribute("date") LocalDate date
) {
    return date;
}

LocalDateFormatterLocalDate从字符串"now""today"和典型的"yyyy-MM-dd"格式的字符串中编码s ,并将日期解码回字符串

public class LocalDateFormatter implements Formatter<LocalDate> {}

我已经通过 Spring Test测试了这个控制器。测试通过

我设置了一个转换服务并用它模拟了一个 MVC:

var conversion = new DefaultFormattingConversionService();
conversion.addFormatterForFieldType(LocalDate.class, new LocalDateFormatter());

mockMvc = MockMvcBuilders
        .standaloneSetup(TimeController.class)
        .setConversionService(conversionRegistry)
        .build();

测试是参数化的,如下所示:

@ParameterizedTest
@MethodSource("args")
void getDate(String rawDate, boolean shouldConvert) throws Exception {
    var getTime = mockMvc.perform(get("/time/" + rawDate));

    if (shouldConvert) {
        // Date is successfully parsed and some JSON is returned
        getTime.andExpect(content().contentType(APPLICATION_JSON_UTF8));
    } else {
        // Unsupported rawDate
        getTime.andExpect(status().is(400));
    }
}

以下是参数:

private static Stream<Arguments> args() {
    // true if string should be parsed
    return Stream.of(
            Arguments.of("now", true),
            Arguments.of("today", true),
            Arguments.of("thisOneShouldNotWork", false),
            Arguments.of("2014-11-27", true)
    );
}

正如我所说,测试通过。

但是从浏览器启动时,任何请求都会收到400错误。

我如何尝试将转换集成到 Spring MVC 中(这些都不起作用):

有人可以告诉我有什么问题吗?

PS我知道这不是处理日期的最佳方式,但由于它在 Spring 参考中说这应该有效,所以我想尝试一下。

标签: javaspring-mvcspring-mvc-test

解决方案


为spring boot定义这个bean:

@Bean
    public Formatter<LocalDate> localDateFormatter() {
        return new Formatter<LocalDate>() {
            @Override
            public LocalDate parse(String text, Locale locale) throws ParseException {
                if ("now".equals(text))
                    return LocalDate.now();
                return LocalDate.parse(text, DateTimeFormatter.ISO_DATE);
            }

            @Override
            public String print(LocalDate object, Locale locale) {
                return DateTimeFormatter.ISO_DATE.format(object);
            }
        };
    }

如果您使用 Spring MVC 定义如下:

@Configuration
@ComponentScan
@EnableWebMvc
public class ServletConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new Formatter<LocalDate>() {
            @Override
            public LocalDate parse(String text, Locale locale) throws ParseException {
                if ("now".equals(text))
                    return LocalDate.now();
                return LocalDate.parse(text, DateTimeFormatter.ISO_DATE);
            }

            @Override
            public String print(LocalDate object, Locale locale) {
                return DateTimeFormatter.ISO_DATE.format(object);
            }
        });
    }
}

不要忘记实现today函数作为参数。


推荐阅读