0 day streak
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
java
1
2
3
4
5
6
7
8
9
10
11
@WebMvcTest(MyController.class)
class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void 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.