DateTime serialization in Spring tests

Vasile Pop
1 min readMay 8, 2018

So here’s the problem: I have some auto-generated tests based on Spring Cloud Contract (more about this amazing thing here) and the DateTime fields are serialized in Json as arrays, not as String.

“creationTime”:[2018,5,8,9,8,39,849000000] instead of “creationTime”:”2018–05–08T09:08:39.849"

This is a reason of failure for all test involving classes having DateTime fields. Normally, this is configured for Spring apps in application.yml:

spring:
jackson:
serialization:
WRITE_DATES_AS_TIMESTAMPS:
false

However, when not using Spring auto-configuration, the tests won’t use the app configuration. So there has to be a way to configure RestAssuredMockMvc in a similar manner. Well, here’s a workaround (I’m sure it can be improved):

MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new
MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setObjectMapper(new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.registerModule(new JavaTimeModule()));
RestAssuredMockMvc.standaloneSetup(
MockMvcBuilders
.standaloneSetup(fooController) .setMessageConverters(mappingJackson2HttpMessageConverter)
);

--

--

Vasile Pop

Skiing in Italy, playing guitars, fancy food, reading, travelling, these are great things and Software Testing is paying for it.