Mock null object in Junit mockMVC

Viewed 217

I am trying to pass null as the content type for JUnit mockMvc but its failing

Object obj =null;
MvcResult result = mockMvc.perform(post("/mgr/v1/processEvent")
    .contentType(MediaType.APPLICATION_JSON)
    .content(String.valueOf(obj))
    .accept(MediaType.APPLICATION_JSON))
    .andDo(print())
    .andExpect(status().is4xxClientError()).andReturn();

its not going inside the controller call

Please help

1 Answers

Don't use String.valueOf(null);. Null is interpreted as a char array which leads to a NullpointerException. Just use an empty String or leave the complete line.

MvcResult result = mockMvc.perform(post("/mgr/v1/processEvent")
    .contentType(MediaType.APPLICATION_JSON)
    .accept(MediaType.APPLICATION_JSON))
    .andDo(print())
    .andExpect(status().is4xxClientError()).andReturn();
Related