A RequestPostProcessor modifies a simulated HTTP request or its execution environment immediately before MockMvc sends it. In security tests, this lets each request define authentication, authorities, roles, or other security conditions without changing the application configuration. section 18.1
Use the supplied Spring Security implementations to prepare common test scenarios:
- Call .with(user("mary")) to attach a mock user to a request. section 18.1
- Call .with(csrf()) to add a CSRF token and verify that a mutating request succeeds; without it, the request returns 403 Forbidden. section 18.6
- Call .with(httpBasic("john", "12345")) to test valid or invalid HTTP Basic credentials. section 18.5
- Use jwt() or opaqueToken() to simulate resource-server authentication. section 18.5
Testing an authenticated endpoint
With Spring Boot and MockMvc configured, perform get("/hello").with(user("mary")), then expect the response body and status. Unlike @WithMockUser, the request is built first and the postprocessor adds the test security environment afterward. section 18.1
Figure 18.5 The difference between using annotations and the RequestPostProcessor to create the test security environment. When using annotations, the framework sets up the test security environment first. When using a RequestPostProcessor, the test request is created and then changed to define other constraints such as the test security environment. In the figure, the points where the framework applies the test security environment are shaded.
Compare annotation-based security setup with request-level preparation: annotations configure the test environment before the method runs, whereas a RequestPostProcessor changes the constructed request before dispatch. section 18.1
