Search code examples
springspring-mvcjunit5spring-mvc-test

Spring MVC Error Handling using Junit 5 and MockMvc class


This post is to perform error handling in Spring MVC 3.

My Testcases were not testing error scenarios as mentioned below.

My Controller class -

@RestController
public class CPCommonServiceController {

    @Autowired
    private MyCommonService MyCommonService;

    @RequestMapping(method = {RequestMethod.GET}, value = "/data", headers = "Accept=application/json")
    public List<Dto> getData() throws ServiceException {
        return myCommonService.getData();
    }
}

Test class-

public class MyControllerTest {
    @InjectMocks
    private MyController myController;

    @Mock
    private MyCommonService myCommonService;

    private MockMvc mockMvc;

    @BeforeEach
    public void setup() {
        MockitoAnnotations.openMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup
                (new MyCommonServiceController()).build();
    }
 @Test
    public void testDataThrowServiceException() throws Exception {
        when(myCommonService.getData())
                .thenThrow(ServiceException.class);

        mockMvc.perform(get("/data"))
                .andExpect(MockMvcResultMatchers.status().is4xxClientError());
    }
}

error occour-

jakarta.servlet.ServletException: Request processing failed: com.exception.ServiceException

    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1022)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903)
    at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:564)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885)

Solution

  • Here what I did to resolve this error---

    I have updated my MyControllerTest class setUp() method as below:

    public void setUp() {
            MockitoAnnotations.openMocks(this);
            this.mockMvc = MockMvcBuilders.standaloneSetup(cpCommonServiceController)
                    .setHandlerExceptionResolvers(getSimpleMappingExceptionResolver())
                    .build();
    
        }
    

    And a new ExceptionResolver method

    SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {
    
        SimpleMappingExceptionResolver result
                = new SimpleMappingExceptionResolver();
    
        // Setting customized exception mappings
        Properties p = new Properties();
        p.put(SimpleMappingExceptionResolver.class.getName(), "Errors/Exception");
        result.setExceptionMappings(p);
    
        // Unmapped exceptions will be directed there
        result.setDefaultErrorView("Errors/Default");
    
        // Setting a default HTTP status code
        result.setDefaultStatusCode(HttpStatus.BAD_REQUEST.value());
    
        return result;
    
    }