Skip to content

Expecting exception during MockMVC.perform in JUnit5

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.

        .content(new ObjctMapper().writeValueAsString(requestObject)

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 at org.springframework.web.servlet.FrameworkServlet.processRequest(
    at org.springframework.web.servlet.FrameworkServlet.doPost(
    at javax.servlet.http.HttpServlet.service(
Caused by:

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.



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.

User contributions licensed under: CC BY-SA
9 People found this is helpful