Authenticating in the @WebMvcTest

Learn authentication by simulating a user login.

Simulating user login

Since our UserController has all its methods secured, we need a way to simulate a user logging in so that we can do some actual validation on the controller’s logic.

The Spring Security test has some helper annotations like @WithMockUser and @WithUserDetails to help us. In our production security configuration, we use DatabaseUserDetailsService and ApplicationUserDetails classes.

As we don’t want to involve a database, we can create a StubUserDetailsService alternative for the automated test by:

  1. Implementing UserDetailsService like our production DatabaseUserDetailsService.

  2. Keeping the users on a Map in memory.

  3. Adding two users in the constructor so they are available for the tests.

  4. Using the users map to search for a matching user.

Get hands-on with 1200+ tech skills courses.