Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Zone for Spring Mock MVC tests

How can the time zone for SpringMock MVC tests be set? Our Spring Boot applications are all running with

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

set at Application startup. But I found no way to set this for the MockMvcRequestBuilders. Setting it manually (in test or BeforeClass) didn't change anything = still machine time-zone is used...

like image 230
Strinder Avatar asked Oct 19 '15 16:10

Strinder


People also ask

What is spring mock MVC?

MockMVC class is part of Spring MVC test framework which helps in testing the controllers explicitly starting a Servlet container. In this MockMVC tutorial, we will use it along with Spring boot's WebMvcTest class to execute Junit testcases which tests REST controller methods written for Spring boot 2 hateoas example.

What is mock MVC used for?

MockMvc provides support for Spring MVC testing. It encapsulates all web application beans and makes them available for testing. We'll initialize the mockMvc object in the @BeforeEach annotated method, so that we don't have to initialize it inside every test.

Which class is used to test spring MVC REST Web application?

We create the test data by using a test data builder class. Configure our mock object to return the created test data when its findAll() method is invoked.


1 Answers

You can do it using a @Configuration class. If you annotate your tests with @SpringBootTest, as Spring loads the context before execute testes, you'll have your default timezone configurated correctly.

I'd just inserted this class below in one of my projects and all my @SpringBootTest annotated tests started to respect UTC timezone. You can replace to use the timezone you want to.

@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;
    }

}
like image 50
Juliano Fernandes Avatar answered Nov 15 '22 07:11

Juliano Fernandes