java - Spring MVC 自定义格式化程序在测试中工作但在浏览器中失败

标签 java spring-mvc spring-mvc-test

我有一个 Controller :(根据 Spring WebMVC @ModelAttribute parameter-style )

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

LocalDateFormatter 从字符串"now""today" 和典型的"对LocalDate 进行编码yyyy-MM-dd"-格式化字符串,并将日期解码回字符串

public class LocalDateFormatter implements Formatter<LocalDate> {}

我已经通过 Spring 测试测试了 这个 Controller 。测试通过

我设置了一个转换服务并用它模拟了一个 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 中(这些都不起作用):

  • 覆盖 WebMvcConfigurer 的方法:

    public class ServletConfig implements WebMvcConfigurer {
        @Override
        public void addFormatters(FormatterRegistry registry) {
            registry.addFormatter(new LocalDateFormatter());
            // ALSO TRIED
            registry.addFormatterForFieldType(LocalDate.class, new LocalDateFormatter());
        }
    }
    
  • 注册一个FormattingConversionService

    @Bean
    public FormattingConversionService conversionService() {
        var service = new FormattingConversionService();
        service.addFormatter(new LocalDateFormatter());
        return service;
    }
    

谁能告诉我哪里出了问题?

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

最佳答案

为 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 函数作为参数。

关于java - Spring MVC 自定义格式化程序在测试中工作但在浏览器中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51291104/

相关文章:

java - Spring-mvc 3.0 应用程序 session 范围

尝试模拟时出现 java.lang.ExceptionInInitializerError

java - 每次鼠标单击时绘制线条,双击时停止绘制

java - 如何用最小库制作左右 channel 的两个FFT对象进行处理

spring - Spring MVC + Hibernate : could not initialize proxy - no Session

spring - 无法为 Spring Controller 的 JUnit 测试加载 ApplicationContext

java - 在 spring test mvc 中设置请求部分

java - 实现特定类的 LinkedList,而不是泛型类型

java - 显示 SVG 文件

spring - 为什么 org.springframework.boot 导入不起作用,但 org.springframework.web 却起作用?