Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How do you test exception handling and @ControllerAdvice with MockMvc? MockMvc के साथ एक्सेप्शन हैंडलिंग और @ControllerAdvice को कैसे टेस्ट करें?

Answer

Since @WebMvcTest loads the full MVC layer, including any @ControllerAdvice classes in the tested package, exception handling can be verified by stubbing a mocked service to throw the target exception and then asserting on the response status and body returned by the global exception handler.

This confirms not just that the controller calls the service correctly, but that the entire error-response pipeline — exception thrown, caught by @ExceptionHandler, mapped to the correct HTTP status and JSON error shape — works end-to-end without needing a full @SpringBootTest.

@Test
void getUser_notFound_returns404() throws Exception {
    when(userService.findById(99L)).thenThrow(new ResourceNotFoundException("User not found"));

    mockMvc.perform(get("/api/users/99"))
        .andExpect(status().isNotFound())
        .andExpect(jsonPath("$.message").value("User not found"));
}

चूंकि @WebMvcTest पूरी MVC लेयर लोड करता है, जिसमें टेस्ट किए गए पैकेज में कोई भी @ControllerAdvice क्लास शामिल है, एक्सेप्शन हैंडलिंग को यह सत्यापित करके जाँचा जा सकता है कि मॉक्ड सर्विस लक्षित एक्सेप्शन फेंके और फिर रिस्पॉन्स स्टेटस व बॉडी पर एसर्ट किया जाए।

यह पुष्टि करता है कि पूरी एरर-रिस्पॉन्स पाइपलाइन — एक्सेप्शन फेंका गया, @ExceptionHandler द्वारा पकड़ा गया, सही HTTP स्टेटस में मैप किया गया — पूरे @SpringBootTest की ज़रूरत के बिना एंड-टू-एंड काम करती है।

@Test
void getUser_notFound_returns404() throws Exception {
    when(userService.findById(99L)).thenThrow(new ResourceNotFoundException("User not found"));

    mockMvc.perform(get("/api/users/99"))
        .andExpect(status().isNotFound())
        .andExpect(jsonPath("$.message").value("User not found"));
}

Was this answer clear?