java / beginner
Snippet
Basic Web Testing with MockMvc
@WebMvcTest focuses only on the web layer of your application. MockMvc allows you to simulate HTTP requests and verify responses without starting a full server.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
@WebMvcTest(MyController.class)class MyControllerTest {@Autowiredprivate MockMvc mockMvc;@Testvoid shouldReturnDefaultMessage() throws Exception {this.mockMvc.perform(get("/hello")).andExpect(status().isOk());}}
spring
Breakdown
1
@WebMvcTest(...)
Focuses only on Spring MVC components and doesn't start a full HTTP server.
2
@Autowired private MockMvc mockMvc
Injects the MockMvc tool to perform and verify web requests.
3
mockMvc.perform(get("/hello"))
Simulates a GET request to the specified endpoint.