liveBook · Manning

Mock user

As explained in Spring Security in Action, Second Edition

A mock user is a test fixture that represents an authenticated user without performing the normal authentication process.

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

How Spring Security in Action, Second Edition covers it

How deep it goes
Defines the security-context boundary and demonstrates annotations, request processors, roles, authorities, and MockMvc scenarios.
Examples
Uses protected /hello calls, @WithMockUser, username mary, roles, authorities, and user("mary") request customization.
What it assumes
Assumes basic Spring testing and security configuration while teaching how authentication and authorization separate through the security context.
What you can do after
Diagnose authorization behavior with controlled authenticated scenarios without repeatedly exercising authentication.
How it connects
Connects authentication, authorization, security context, MockMvc, and method security.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.