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...
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.
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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With