java / beginner
Snippet
Testing Web Endpoints in Isolation Using MockMvc
The @WebMvcTest annotation loads only the Spring MVC infrastructure and the specified controller without spinning up a full HTTP server. MockMvc allows you to simulate incoming HTTP GET/POST requests and make fluent assertions on response statuses, headers, and body payloads, providing fast and reliable controller tests.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@RestController@RequestMapping("/api/hello")public class HelloController {@GetMappingpublic String sayHello() {return "Hello Spring!";}}@WebMvcTest(HelloController.class)public class HelloControllerTest {@Autowiredprivate MockMvc mockMvc;@Testpublic void testSayHelloEndpoint() throws Exception {mockMvc.perform(MockMvcRequestBuilders.get("/api/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().string("Hello Spring!"));}}
spring
Breakdown
1
@WebMvcTest(HelloController.class)
Focuses the test context solely on the web layer for HelloController, skipping database and service beans.
2
mockMvc.perform(MockMvcRequestBuilders.get("/api/hello"))
Simulates sending an HTTP GET request to the '/api/hello' endpoint.
3
.andExpect(MockMvcResultMatchers.status().isOk())
Asserts that the HTTP response status code returned by the controller is 200 OK.