concept mock user in category spring

appears as: mock users, mock user, The mock user, mock users
Spring Security in Action

This is an excerpt from Manning's book Spring Security in Action.

20.1  Using mock users for test

In this section, we discuss using mock users to test the authorization configuration. This approach is the most straightforward but also the most used for testing authorization configurations. When using a mock user, the test completely skips the authentication (figure 20.3). The mock user is valid only for the test execution, and you can configure for this user any characteristics you need to validate a specific scenario. You could, for example, give specific roles to the user, ADMIN or MANAGER, or different authorities to validate that the app behaves as expected in these conditions.

Figure 20.3 The components shaded differently from the Spring Security authentication flow are skipped when executing a test. The test directly uses a mock SecurityContext, which contains the mock user you define to call the tested functionality.

Run this test now and observe it’s successful. But in some situations, to implement the test, we need to use a specific name or give the user specific roles or authorities. Say we want to test the endpoints we defined for example ssia-ch5-ex2. For this example, the endpoints return a body depending on the authenticated user’s name. So, to write the test, we need to give the user a known username. Listing 20.5 shows you how to configure the details of the mock user by writing a test for the /hello endpoint of the ssia-ch5-ex2 project.

Listing 20.5 Configuring details for the mock user
@SpringBootTest
@AutoConfigureMockMvc
public class MainTests {
    
     // Omitted code
 
  @Test
  @WithMockUser(username = "mary")    #A
  public void helloAuthenticated() throws Exception {
    mvc.perform(get("/hello"))
         .andExpect(content().string("Hello, mary!"))
         .andExpect(status().isOk());
    }
}

#A Setting up a username for the mock user.