我正在尝试验证Spring MVC Web服务返回的JSON结果中的LocalDate对象,但我不知道如何。
目前,我总是遇到如下断言错误:
java.lang.AssertionError: JSON 路径 "$[0].startDate" 预期: 是 <2017-01-01> 但是:是<[2017,1,1]>
我的测试的重要部分发布在下面。任何想法如何修复测试以通过?
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))));
}
}
Web 服务返回如下所示的视图对象列表:
public class ViewObject {
@JsonProperty
private LocalDate startDate;
}
[编辑]
另一个尝试是
.andExpect(jsonPath("$[0].startDate", is(new int[] { 2017, 1, 1 })))
这导致了
java.lang.AssertionError: JSON 路径 "$[0].startDate" 预期: 是 [<2017>, <1>, <1>] 但是:是<[2017,1,1]>
[编辑2]返回的 startDate 对象似乎类型为:net.minidev.json.JSONArray
这应该通过:
.andExpect(jsonPath("$[0].startDate", is(LocalDate.of(2017, 1, 1).toString())));
这是要走的路。感谢"Amit K Bist"为我指明了正确的方向
...
.andExpect(jsonPath("$[0].startDate[0]", is(2017)))
.andExpect(jsonPath("$[0].startDate[1]", is(1)))
.andExpect(jsonPath("$[0].startDate[2]", is(1)))
响应中的 LocalDate 将类似于"startDate":
"startDate": {
"year": 2017,
"month": "JANUARY",
"dayOfMonth": 1,
"dayOfWeek": "SUNDAY",
"era": "CE",
"dayOfYear": 1,
"leapYear": false,
"monthValue": 1,
"chronology": {
"id": "ISO",
"calendarType": "iso8601"
}
}
因此,您应该像下面一样检查每个属性:
.andExpect(jsonPath("$[0].startDate.year", is(2017)))
.andExpect(jsonPath("$[0].startDate.dayOfMonth", is(1)))
.andExpect(jsonPath("$[0].startDate.dayOfYear", is(1)))
因为它需要一个值列表,所以你可以这样使用它。
.andExpect(jsonPath("$[0].startDate", is(List.of(2022, 1, 1))))
在该级别您验证的是 Json 而不是解析的对象。所以你有一个字符串,而不是一个 LocalDate。
所以基本上尝试更改你的代码:
...
.andExpect(jsonPath("$[0].startDate", is("2017-01-01"))));