0

I got a java.lang.AssertionError when I was attempting to verify the href. The response body looks fine,

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 = []

but when called this sentence: andExpect(jsonPath("$.links[0].href", hasItem(endsWith("/items/001"))))

The error occured:

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)

Here is the test code:

@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());

Can anyone figure out where is wrong?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Frank
  • 5
  • 1
  • 4

1 Answers1

0

The actual result of jsonPath(...) for "$.links[0].href" is just a String as stated in the AssertionError.

The expected result for hasItem(...) is a collection as stated in the AssertionError.

In your case therefore just use endsWith(...) withouch hasItem(...). If your expression for jsonPath(...) returns a collection (e.g. via "$.links[*].href") instead of a single item you should use hasItem(...).

René Scheibe
  • 1,970
  • 2
  • 14
  • 20
  • Jus changed to "andExpect(jsonPath("$.links[0].href", CoreMatchers.endsWith("/items/001")))", and it works. – Frank Jan 31 '17 at 23:18