Spring Test returning 401 for unsecured URLs

后端 未结 4 1587
北荒
北荒 2020-12-07 00:38

I am using Spring for MVC tests

Here is my test class

@RunWith(SpringRunner.class)
@WebMvcTest
public class ITIndexController {

    @Autowired
    W         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 01:19

    I found the answer
    Spring docs says that:

    @WebMvcTest will auto-configure the Spring MVC infrastructure and limit scanned beans to @Controller, @ControllerAdvice, @JsonComponent, Filter, WebMvcConfigurer and HandlerMethodArgumentResolver. Regular @Component beans will not be scanned when using this annotation.

    And according to this issue in github:

    https://github.com/spring-projects/spring-boot/issues/5476

    The @WebMvcTest by default auto configure spring security if spring-security-test is present in the class path (which in my case is).

    So since WebSecurityConfigurer classes aren't picked, the default security was being auto configured, that is the motive I was receiving the 401 in url's that was not secured in my security configuration. Spring security default auto configuration protects all url's with basic authentication.

    What I did to solve the problem was to annotate the class with @ContextConfiguration, and @MockBean like it is described in the documentation:

    Often @WebMvcTest will be limited to a single controller and used in combination with @MockBean to provide mock implementations for required collaborators.

    And here is the test class

    @RunWith(SpringRunner.class)
    @WebMvcTest
    @ContextConfiguration(classes={Application.class, MvcConfig.class, SecurityConfig.class})
    public class ITIndex {
    
        @Autowired
        WebApplicationContext context;
    
        MockMvc mockMvc;
    
        @MockBean
        UserRegistrationApplicationService userRegistrationApplicationService;
    
        @MockBean
        UserDetailsService userDetailsService;
    
        @Before
        public void setUp() {
            this.mockMvc = MockMvcBuilders
                            .webAppContextSetup(context)
                            .apply(springSecurity())
                            .build();
        }
    
        @Test
        public void should_render_index() throws Exception {
            mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(view().name("index"))
                .andExpect(content().string(containsString("Login")));
        }
    }
    

    Application, MvcConfig and SecurityConfig are all my configuration classes

提交回复
热议问题