Disable security for unit tests with spring boot

UPDATE to ANSWER:
Another option i recently learned if I am using MockMvc and AutoConfigureMockMvc to test my controllers, i can just set secure=false on it to disable any security applicable to your controllers.

@AutoConfigureMockMvc(secure = false)

If not go with below for basic auth.


The exception you get is very different than what i was getting but if you want to disable the security while running test cases, you can trying using profiles and disabling the basic security using properties for test profile. This is what i did –

  1. Added annotation @Profile(value = {"development", "production"}) to my implementation of WebSecurityConfigurerAdapter
    @Configuration
    @EnableWebSecurity
    @Profile(value = {"development", "production"})
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

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

3. 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 disabled the security for my test cases and i was able to access the authenticated urls. I hope this works for you too. Best of luck!!!

Leave a Comment