springspring-testspring-test-mvc

Spring MockMvc verify body is empty


I have a simple Spring test

@Test
public void getAllUsers_AsPublic() throws Exception {
    doGet("/api/users").andExpect(status().isForbidden());
}

public ResultActions doGet(String url) throws Exception {
    return mockMvc.perform(get(url).header(header[0],header[1])).andDo(print());
}

I would like to verify that the response body is empty. E.g. Do something like .andExpect(content().isEmpty())


Solution

  • There's a cleaner way:

    andExpect(jsonPath("$").doesNotExist())
    

    Note that you can't use isEmpty because it checks for an empty value, and assumes the existence of the attribute. When the attribute doesn't exist, isEmpty throws an exception. Whereas, doesNotExist verifies that the attribute doesn't exist, and when used with $, it checks for an empty JSON document.