Spring boot, disable security for tests

后端 未结 2 2088
长情又很酷
长情又很酷 2021-02-20 07:55

I use spring boot version \"1.3.0.M5\" (I also tried version \"1.2.5.RELEASE\"). I added spring security:


  org.springframework         


        
2条回答
  •  不要未来只要你来
    2021-02-20 08:30

    If you want to see what's being auto-configured, launch your web app and access the autoconfig endpoint (e.g., http://localhost:8080/autoconfig). Then search for 'Security' to see which 'AutoConfiguration' classes are being detected.

    You can then disable auto-configuration of security by excluding those classes like this:

    @EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class, ManagementSecurityAutoConfiguration.class })
    

    Of course, you won't want to exclude them for production deployments. Thus you'll need to have a separate @Configuration class for production and tests.

    Or if you want a detailed answer go for below-mentioned steps


    Add annotation @Profile(value = {"development", "production"}) to my implementation of WebSecurityConfigurerAdapter

    @Configuration
        @EnableWebSecurity
        @Profile(value = {"development", "production"})
        public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    

    Now, in test/resources, create application-test.yml to define properties for test profile and add this -

    # Security enable/disable
    security:
      basic:
        enabled: false
    

    Now, to your test cases, add this annotation to apply the active profile @ActiveProfiles(value = "test"). This is how my class looked -

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = Application.class)
    @WebAppConfiguration
    @ActiveProfiles(value = "test")
    @IntegrationTest({"server.port=0"})
    public class SampleControllerIntegrationTest {
    

    Doing this will disabled security for tests. Best of luck!!!

提交回复
热议问题