Spring Mock MVC测试的时区

Str*_*der 3 spring spring-mvc spring-boot

如何设置SpringMock MVC测试的时区?我们的Spring Boot应用程序都与

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Run Code Online (Sandbox Code Playgroud)

在应用程序启动时设置。但是我没有办法为MockMvcRequestBuilders设置它。手动设置(在测试或BeforeClass中)没有任何改变=仍在使用机器时区...

小智 5

您可以使用@Configuration类来实现。如果您使用@SpringBootTest注释测试,那么在Spring在执行testes之前加载上下文时,您将正确配置默认时区。

我刚刚在一个项目中将此类插入下面,并且所有带有@SpringBootTest注释的测试都开始遵守UTC时区。您可以替换以使用所需的时区。

@Configuration
public class TimeZoneConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(TimeZoneConfig.class);

    @Bean
    public TimeZone timeZone(){
        TimeZone defaultTimeZone = TimeZone.getTimeZone("UTC");
        TimeZone.setDefault(defaultTimeZone);
        LOGGER.info("Spring boot application running in UTC timezone :"+new Date());
        return defaultTimeZone;
    }

}
Run Code Online (Sandbox Code Playgroud)