问题
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
回答1:
LocalDate in JSON response will be like "startDate":
"startDate": {
"year": 2017,
"month": "JANUARY",
"dayOfMonth": 1,
"dayOfWeek": "SUNDAY",
"era": "CE",
"dayOfYear": 1,
"leapYear": false,
"monthValue": 1,
"chronology": {
"id": "ISO",
"calendarType": "iso8601"
}
}
So, you should check each attribute like below:
.andExpect(jsonPath("$[0].startDate.year", is(2017)))
.andExpect(jsonPath("$[0].startDate.dayOfMonth", is(1)))
.andExpect(jsonPath("$[0].startDate.dayOfYear", is(1)))
回答2:
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)))
回答3:
This should pass:
.andExpect(jsonPath("$[0].startDate", is(LocalDate.of(2017, 1, 1).toString())));
回答4:
I think that at that level you are validating the Json not the parsed object. So you have a string, not a LocalDate.
So basically try changing your code in:
...
.andExpect(jsonPath("$[0].startDate", is("2017-01-01"))));
来源:https://stackoverflow.com/questions/46649311/validate-localdate-in-json-response-with-spring-mockmvc