Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 306
isADon Avatar asked Sep 26 '17 07:09

isADon


People also ask

What is MockMvc standaloneSetup?

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 .

Is MockMvc thread safe?

From a technical point of view MockMvc is not thread-safe and shouldn't be reused.


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.

like image 102
Abhijit Sarkar Avatar answered Oct 10 '22 11:10

Abhijit Sarkar


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("")) 
like image 25
DaveyDaveDave Avatar answered Oct 10 '22 10:10

DaveyDaveDave