Spring MockMvc verify body is empty

Viewed 24079

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

2 Answers

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.

I think one of these options should achieve what you're looking for, although not quite as nice as an isEmpty() (from the ContentResultMatchers documentation):

.andExpect(content().bytes(new Byte[0])

or

.andExpect(content().string(""))
Related