简体   繁体   中英

Spring @Configuration not overriden in test context

Today I updated my project from Spring Boot 1.5.9 to 2.1.1, and some of my tests stopped working. When i start the tests, error pops on console:

Field authEntryPoint in com.example.rest.config.SecurityConfig required a bean of type 'com.example.rest.service.auth.entrypoints.AuthenticationEntryPoint' that could not be found.

The problem is I have bean of this type defined in my SecurityConfig class, but I am overriding this configuration in my test package in TestApplication class. Security config is defined there as static inner class. I have tried different approaches including Spring profiles and @Primary annotation, but nothing seems to work and Spring doesn't pick my test configuration like it did before. Only thing that worked was when I deleted the non-test version of SecurityConfig class and test version became only bean of this type.

Can someone tell me how do I override this original configuration or how to turn off Spring Security just for testing? Or maybe there is a way to force Spring not to pick up that non-test @Configuration bean?

SecurityConfig.class

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        AuthenticationEntryPoint authEntryPoint;

        @Autowired
        BasicAuthenticationProvider basicAuthProvider;

        @Autowired
        PreAuthenticatedUserDetailsService preAuthUserDetailsService;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/rest/query/id/*/user/*",
                            "/rest/files/**/*").hasAnyRole("CLIENT", "SYSTEM")
                    .antMatchers("/public/api/management/**/*").hasRole("SYSTEM")
                    .antMatchers("/public/api/**/*").hasAnyRole("SYSTEM", "USER")
                    .antMatchers("/rest/**/*").hasRole("SYSTEM")
                    .and()
                .x509()
                    .userDetailsService(preAuthUserDetailsService)
                    .and()
                .httpBasic()
                    .authenticationEntryPoint(authEntryPoint)
                    .and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and().csrf().disable();
        }

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {       
            auth.authenticationProvider(basicAuthProvider);     
        }

        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/").antMatchers("/rest/files/name/**");
        }
    }

Test SpringBootClass with SecurityConfig inside

@SpringBootApplication public class TestApplication {

@Configuration
@EnableWebSecurity
public static class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**").permitAll()
        .and().csrf().disable();
    }
}

}

Example test from the suite

@RunWith(SpringRunner.class)
@WebMvcTest(DocumentManagementController.class)
public class DocumentManagementControllerTests {

    @Autowired
    MockMvc mvc;

    @MockBean
    SystemMetadataService systemMetadataService;

    @MockBean
    CustomMetadataService customMetadataService;

    @MockBean
    PrinterService printerService;

    @MockBean
    EventLoggerService eventLoggerService;

    @Captor ArgumentCaptor<String> systemCaptor;
    @Captor ArgumentCaptor<String> clientCaptor;
    @Captor ArgumentCaptor<Boolean> holdCaptor;
    @Captor ArgumentCaptor<String> retentionCaptor;
    @Captor ArgumentCaptor<String> objectPathCaptor;
    @Captor ArgumentCaptor<Boolean> accessCaptor;
    @Captor ArgumentCaptor<Boolean> manualProcessingCaptor;
    @Captor ArgumentCaptor<Boolean> incorrectCaptor;
    @Captor ArgumentCaptor<Integer> statusCaptor;
    @Captor ArgumentCaptor<Boolean> noTemplateCaptor;

    @Test
    public void setDocumentAccess_givenProperData_shouldReturnOk() throws Exception {
        when(customMetadataService.setDocumentAccess(anyString(), anyBoolean()))
        .then(inv -> new HcpCreateObjectResult(inv.getArgument(0)));

        Boolean accessForbidden = true; String objectPath = "path";

        mvc.perform(get("/rest/management/access/forbid/"+accessForbidden+"?objectPath="+objectPath))
        .andExpect(status().isOk());

        verify(customMetadataService).setDocumentAccess(objectPathCaptor.capture(), accessCaptor.capture());
        assertThat(objectPathCaptor.getValue(), is(equalTo(objectPath)));
        assertThat(accessCaptor.getValue(), is(equalTo(accessForbidden)));
    }

I managed to do make this work using @Profile and @ActiveProfiles . But i had to extract my static inner @Configuration class to another java file and then it automagically started to work. Still haven't found why it worked in earlier version of Spring Boot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM