MockMvc performs simulated HTTP requests against Spring MVC components, allowing endpoint behavior and security configuration to be tested without a running server. section 18.1
A typical security test workflow is:
- Annotate the test with @SpringBootTest and @AutoConfigureMockMvc, then autowire MockMvc. section 18.1
- Call an endpoint with mvc.perform(get("/hello")) and assert the response status or content. section 18.1
- Test unauthenticated and authenticated paths separately by omitting a user or adding one with @WithMockUser or user("mary"). section 18.1
Listing 18.2 Adding MockMvc for implementing test scenarios
@SpringBootTest
@AutoConfigureMockMvc #1
public class MainTests {
@Autowired
private MockMvc mvc; #2
}
Shows the minimal @AutoConfigureMockMvc setup and injected MockMvc field used to implement endpoint scenarios. section 18.1
