5

I'm writing unit tests for Spring MVC 4.2.x REST controllers and have an issue with dates serialized by Jackson (2.6.x). While running the application the dates (java.util.Date) are serialized in the format yyyy-MM-dd by default (no extra configuration), which is what I want.

However during tests the dates are serialized as timestamps for an unknown reason.

Here's some sample code for the test class:

public class OrderControllerTest {

    @Mock
    private OrderService service;

    @InjectMocks
    private OrderController controller;

    private MockMvc mockMvc;

    private List<Order> orders = new ArrayList<>();

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        // Initialize dummy order list
        orders.add(...);
        orders.add(...);
        orders.add(...);
    }

    @Test
    public void list() throws Exception {
        // Stub the service find method
        when(service.find(asOfDate, null)).thenReturn(orders);

        // Run the controller and check the result
        MvcResult result =
            mockMvc
                .perform(get("/admin/order/"))
                .andExpect(status().isOk())
                .andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
                .andExpect(jsonPath("$[0].startDate", is(SOME_DATE)))
                .andReturn();

        System.out.println(result.getResponse().getContentAsString());
    }

So here I see that the dates returned are all timestamps.

Surefire output:

Expected: is <Thu Jan 01 00:00:00 CET 2015>
     but: was <1420066800000L>

Am I missing something? Why is the default serialization format different for running the application and for running tests?

yktoo
  • 2,696
  • 1
  • 23
  • 35
  • Are you sure Jackson was not customized in our configuration classes/files? By default it serializes dates as numbers, if I'm not mistaken. – Marlon Bernardes Dec 09 '15 at 13:31
  • Nothing that I could find in the code. `jackson-databind` is simply added to the `pom.xml`, that's it. – yktoo Dec 09 '15 at 13:41
  • 3
    How did you solve this? – Kaushal28 Mar 08 '18 at 09:16
  • Hi, I solved using `.andExpect(jsonPath("$.publishDate", Matchers.is(docFound.getPublishDate().getTime())));`. Maybe this can help someone. – Leo Jun 25 '18 at 11:09

0 Answers0