Run unit tests on controllers that require authentication

后端 未结 1 1164
轻奢々
轻奢々 2020-12-30 10:35

I have a spring boot application which requires login for some actions. I am trying to test them using MockMvc, but it doesn\'t seem to work. I keep getting a H

1条回答
  •  有刺的猬
    2020-12-30 11:10

    You need to specify which user you want to run the test as. You have a few options (each option is a link to the detailed documentation):

    @WithMockUser

    This option will create a fake user (i.e. the user does not need to exist in a data store). The problem with this approach is if your application relies on a custom User implementation you may get class cast Exceptions. If you do not return a custom type from a custom UserDetailsService, then this solution should work fine.

     @Test
     @WithMockUser(username="admin",roles={"USER","ADMIN"})
     public void changePasswordWorks() throws Exception {
    

    @WithUserDetails

    If you implemented a custom UserDetailsService that returns a custom implementation of UserDetails, this solution may work for you.

    For it to work you need to expose a UserDetailsService as a Bean and the user must exist. For example:

     @Test
     @WithUserDetails("admin")
     public void changePasswordWorks() throws Exception {
    

    @WithSecurityContext

    This is the best of both worlds, but requires a little additional setup. If you have a custom UserDetailsService returning a custom implementation of UserDetails and do NOT want the user to necessarily have to exist you can use this method. I'll let you read the documentation on this setup as it is a bit more lengthy and well documented.

    Using a RequestPostProcessor

    If annotations aren't your thing you can use a RequestPostProcessor. For example:

    import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
    
     ...
    
     @Test
     public void changePasswordWorks() throws Exception {
         // Send password change request
         PasswordChangeRepresentation passwordChange = new PasswordChangeRepresentation(DefaultUsers.Admin.getPassword(), "12345678");
         mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.POST, "/password/change")
    
                 // ADD this line
                 .with(user("admin").roles("USER","ADMIN"))
    
                 .content(new ObjectMapper().writeValueAsString(passwordChange))
                 .contentType(MediaType.APPLICATION_JSON)
                 .accept(MediaType.APPLICATION_JSON))
                 .andExpect(status().isOk());
    
         // Check that the password has been changed
         User user = this.userRepository.findByUsername(DefaultUsers.Admin.getEmail());
         Assert.assertEquals(user.getPassword(), "12345678");
    }
    

    0 讨论(0)
提交回复
热议问题