Expecting exception during MockMVC.perform in JUnit5

Tags: , , ,



This may be a repeated question. But I have gone through some 10-15 related posts and associated responses which have not resolved my issue. The issue that I am facing is as here below I have a SpringRest controller class with custom ApplicationException. I have written a Junit for my controller and here below is the snippet where I am facing issue.

this.mockMvc.perform(MockMvcRequestBuilders.post(url)
        .contentType(MediaType.APPLICATION_JSON)
        .content(new ObjctMapper().writeValueAsString(requestObject)
        .headers(header)
        .accept(MediaType.APPLICATION_JSON)
    )
    .andDo(print())
    .andExpect(status().is4xxClientError());

When I execute the test method, I see that ApplicationException is thrown from the code, but the Junit fails and what I see in Junit Console is

"org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.abc.pmr.case.exception.ApplicationException at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
...
...
Caused by: com.abc.pmr.case.exception.ApplicationException
    at com.abc.pmr.case.exception.ApplicationException

I tried with .andExpect(mvcresult -> assertTrue(mvcresult.getResolvedException() instanceof ApplicationException)); as well. But that did not help either.

The Junit fails with the above said exception, while I want to pass the Junit with the expected Exception as ApplicationException. Note: All the success scenario testcases in this class are passing successfully.

Any help here would be much appreciated.

Answer

I suppose that your mockMvc setup is not completely correct for your case. Make sure that you have set exception handler to your mockMvc. You can find more info about this here.

So, when your environment will be configured correct you will have an ability test this logic.



Source: stackoverflow