jsonspringspring-mvcmockmvc

Validate LocalDate in JSON response with Spring MockMVC


I'm trying to validate a LocalDate object in a JSON result returned by a Spring MVC webservice but I can't figure out how.

At the moment I always run into assertion errors like the following one:

java.lang.AssertionError: JSON path "$[0].startDate" Expected: is <2017-01-01> but: was <[2017,1,1]>

The important part of my test is posted below. Any ideas how to fix the test to pass?

import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

public class WebserviceTest {

    @Mock
    private Service service;

    @InjectMocks
    private Webservice webservice;

    private MockMvc mockMvc;

    @Before
    public void before() {
        mockMvc = standaloneSetup(webservice).build();
    }

    @Test
    public void testLocalDate() throws Exception {
        // prepare service mock to return a valid result (left out)

        mockMvc.perform(get("/data/2017")).andExpect(status().isOk())
            .andExpect(jsonPath("$[0].startDate", is(LocalDate.of(2017, 1, 1))));
    }
}

The webservice returns a list of view objects looking like this:

public class ViewObject {

    @JsonProperty
    private LocalDate startDate;
}

[edit]

Another try was

.andExpect(jsonPath("$[0].startDate", is(new int[] { 2017, 1, 1 })))

which resulted in

java.lang.AssertionError: JSON path "$[0].startDate" Expected: is [<2017>, <1>, <1>] but: was <[2017,1,1]>

[edit 2] The returned startDate object seems to be of type: net.minidev.json.JSONArray


Solution

  • This is the way to go. Thanks to 'Amit K Bist' to point me in the right direction

    ...
    .andExpect(jsonPath("$[0].startDate[0]", is(2017)))
    .andExpect(jsonPath("$[0].startDate[1]", is(1)))
    .andExpect(jsonPath("$[0].startDate[2]", is(1)))