Sobes.tech
Junior — Middle

Can you explain what the @WebMvcTest annotation means in the context of testing Spring applications?

sobes.tech AI

Answer from AI

The @WebMvcTest annotation is used in Spring for testing the web layer controllers. It loads only components related to the web layer (such as controllers, Spring MVC configurations, filters), without loading the entire application context.

This allows for writing fast and isolated controller tests without affecting services, repositories, and other beans. Usually, MockMvc is used together with @WebMvcTest to simulate HTTP requests and verify responses.

Example:

@WebMvcTest(MyController.class)
public class MyControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testGet() throws Exception {
        mockMvc.perform(get("/api/data"))
               .andExpect(status().isOk())
               .andExpect(content().string("Hello"));
    }
}
Can you explain what the @WebMvcTest annotation means… - sobes.tech