我试图验证Spring MVC webservice返回的JSON结果中的LocalDate对象,但我无法弄清楚方法。使用Spring MockMVC验证JSON响应中的LocalDate
此时,我总会遇到这样的断言错误类似以下:
java.lang.AssertionError: JSON path "$[0].startDate" Expected: is <2017-01-01> but: was <[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))));
}
}
WebService的返回视图对象的寻找像这样的列表:
public class ViewObject {
@JsonProperty
private LocalDate startDate;
}
[编辑]
另一种尝试是
.andExpect(jsonPath("$[0].startDate", is(new int[] { 2017, 1, 1 })))
这就造成了
java.lang.AssertionError: JSON path "$[0].startDate" Expected: is [<2017>, <1>, <1>] but: was <[2017,1,1]>
[编辑2] 返回的startDate对象似乎是类型:net.minidev.json.JSONArray
这导致到java.lang.AssertionError:JSON路径“$ [0] .startDate” 预计:是“2017年1月1日” 但是:是<[2017,1,1]> – GreenTurtle