A mock user is a test-only authenticated user that lets security tests evaluate authorization without performing the normal authentication process. The test places the user in a mock SecurityContext, then calls the protected functionality. section 18.1
Use a mock user to:
- Test whether an endpoint or method allows an authenticated request. section 18.1
- Configure usernames, roles, and authorities for specific authorization scenarios. section 18.1
- Keep authentication tests separate from the larger set of authorization tests. section 18.9
Testing an authenticated endpoint
With Spring Security test support and MockMvc, annotate a test with @WithMockUser, call /hello, and expect a successful response. Without a mock user, the same protected call can be expected to return 401 Unauthorized. Configure a username such as mary when the endpoint response depends on the authenticated name. Alternatively, attach user("mary") to the request with a RequestPostProcessor. section 18.1
Figure 18.3 We skip the shaded components in the Spring Security authentication flow when executing a test. The test directly uses a mock SecurityContext, which contains the mock user you define to call the tested functionality.
Shows how a test skips authentication components and directly uses a mock SecurityContext containing the configured user. section 18.1
