How to check String in response body with mockMvc

后端 未结 12 1904
遇见更好的自我
遇见更好的自我 2020-12-02 04:02

I have simple integration test

@Test
public void shouldReturnErrorMessageToAdminWhenCreatingUserWithUsedUserName()          


        
12条回答
  •  孤城傲影
    2020-12-02 04:54

    Reading these answers, I can see a lot relating to Spring version 4.x, I am using version 3.2.0 for various reasons. So things like json support straight from the content() is not possible.

    I found that using MockMvcResultMatchers.jsonPath is really easy and works a treat. Here is an example testing a post method.

    The bonus with this solution is that you're still matching on attributes, not relying on full json string comparisons.

    (Using org.springframework.test.web.servlet.result.MockMvcResultMatchers)

    String expectedData = "some value";
    mockMvc.perform(post("/endPoint")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(mockRequestBodyAsString.getBytes()))
                    .andExpect(status().isOk())
                    .andExpect(MockMvcResultMatchers.jsonPath("$.data").value(expectedData));
    

    The request body was just a json string, which you can easily load from a real json mock data file if you wanted, but I didnt include that here as it would have deviated from the question.

    The actual json returned would have looked like this:

    {
        "data":"some value"
    }
    

提交回复
热议问题