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())
We set up the MockMvc . We add the MyController to the standalone setup. The MockMvcBuilders. standaloneSetup allows to register one or more controllers without the need to use the full WebApplicationContext .
From a technical point of view MockMvc is not thread-safe and shouldn't be reused.
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(""))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With