Subjects

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

How does @WebMvcTest work, and how is it different from @SpringBootTest? @WebMvcTest कैसे काम करता है, और यह @SpringBootTest से कैसे अलग है?

Answer

@WebMvcTest loads only the Spring MVC layer — controllers, @ControllerAdvice, filters, and MVC-related configuration — without starting the full application context, so services, repositories, and the database are not loaded by default and must be provided as @MockBeans.

This makes it much faster than @SpringBootTest and ideal for testing controller behavior in isolation: request mapping, validation, status codes, and JSON serialization, using MockMvc to perform simulated HTTP requests without starting a real server.

@WebMvcTest(UserController.class)
class UserControllerTest {
    @Autowired private MockMvc mockMvc;
    @MockBean private UserService userService;

    @Test
    void getUser_returns200() throws Exception {
        when(userService.findById(1L)).thenReturn(new User(1L, "John"));
        mockMvc.perform(get("/api/users/1"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.name").value("John"));
    }
}

@WebMvcTest केवल स्प्रिंग MVC लेयर लोड करता है — कंट्रोलर्स, @ControllerAdvice, फ़िल्टर्स और MVC-संबंधित कॉन्फिगरेशन — बिना पूरा एप्लिकेशन कॉन्टेक्स्ट शुरू किए, इसलिए सर्विसेज़, रिपॉज़िटरीज़ और डेटाबेस डिफ़ॉल्ट रूप से लोड नहीं होते।

यह इसे @SpringBootTest से काफी तेज़ बनाता है और कंट्रोलर व्यवहार को अलग करके टेस्ट करने के लिए आदर्श है, MockMvc का उपयोग करके सिम्युलेटेड HTTP रिक्वेस्ट्स करते हुए।

@WebMvcTest(UserController.class)
class UserControllerTest {
    @Autowired private MockMvc mockMvc;
    @MockBean private UserService userService;

    @Test
    void getUser_returns200() throws Exception {
        when(userService.findById(1L)).thenReturn(new User(1L, "John"));
        mockMvc.perform(get("/api/users/1"))
            .andExpect(status().isOk());
    }
}

Was this answer clear?