我在尝试验证href时遇到了java.lang.AssertionError。响应主体看起来很好,
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"itemName":"ThinkPad","links":[{"rel":"self","href":"http://localhost/items/001"}]}
Forwarded URL = null
Redirected URL = null
Cookies = []
但是在调用这句话时:andExpect(jsonPath("$.links[0].href", hasItem(endsWith("/items/001"))))
发生错误:
java.lang.AssertionError: JSON path "$.links[0].href"
Expected: a collection containing ""
but: was "http://localhost/items/001"
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:74)
at org.springframework.test.web.servlet.result.JsonPathResultMatchers$1.match(JsonPathResultMatchers.java:86)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at scnz.api.controller.ItemDispatchControllerTest.getCurrentStock(ItemDispatchControllerTest.java:62)
这是测试代码:
@Test
public void getCurrentStock() throws Exception {
Item item = new Item("001", "ThinkPad");
when(service.retrieve("001")).thenReturn(item);
mockMvc.perform(get("/items/001"))
.andDo(print())
.andExpect(jsonPath("$.itemName", is(item.getItemName())))
.andExpect(jsonPath("$.links[0].href", hasItem(endsWith("/items/001"))))
.andExpect(status().isOk());
任何人都可以找出错误的地方吗?
答案 0 :(得分:0)
jsonPath(...)
for" $。links [0] .href"的实际结果只是一个字符串,如AssertionError中所述。
hasItem(...)
的预期结果是AssertionError中所述的集合。
因此,在您的情况下,只需使用endsWith(...)
withouch hasItem(...)
即可。如果jsonPath(...)
的表达式返回一个集合(例如通过" $。links [*]。href")而不是单个项目,则应使用hasItem(...)
。