import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.web.servlet.MockMvc; import org.junit.jupiter.api.Test; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @WebMvcTest(HelloController.class) class HelloControllerTest { @Autowired private MockMvc mockMvc; @Test void testHelloEndpoint() throws Exception { mockMvc.perform(get("/hello")) .andExpect(status().isOk()); } } @RestController class HelloController { @GetMapping("/hello") public String hello() { return "Hello World"; } }
@WebMvcTest loads only the specified controller and configures MockMvc for testing web layer. The /hello endpoint exists and returns 200 OK, so the test passes.
mockMvc.perform(get("/api/status"))jsonPath allows checking specific JSON fields. Option C correctly asserts the message field value. Option C is valid JSON but less precise. Option C is invalid JSON string. Option C checks wrong content type.
@WebMvcTest loads only the controllers specified. If the tested controller is not included, the endpoint is not mapped, causing 404.
@WebMvcTest loads only web layer beans. Service beans must be mocked or provided manually. Otherwise, Spring throws NoSuchBeanDefinitionException.
@WebMvcTest is designed to test only the web layer, loading controllers and related MVC components, not the full application context.