Disable Spring Security config class for @WebMvcTest in Spring Boot

Johan :

Recently I have added Spring Security to my Spring Boot project using the following class:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MySecurityConfig {
}

as result, by default all my URLs are now protected with authentication and a self-generated password.

The problem is that all tests in a @WebMvcTest class that I used for unit-testing a controller:

@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class SomeControllerTest {...}

are now failing everywhere because of lack of authorization.

Question: can I tell @Test methods to ignore authorization so they keep succeeding as before?

How can I prevent the @EnableWebSecurity config class from being picked on a specific @WebMvcTest unit testing class?

I would like the tests already in place to be able to still go through and to test the authentication features separately later on.

So far I have tried to use a nested config class in the testing class in order to exclude security configs:

@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class SomeControllerTest {

    @Configuration
    @EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class})
    static class ContextConfiguration { }

 ....}

but it seems not to work.

NOTE : I am using Spring Boot 1.5.8

Mzzl :

You can set secure=false in the @WebMvcTest annoation. It will skip the spring security MockMvc auto configuration in your Test

@WebMvcTest(controllers = SomeController.class, secure = false)
public class SomeControllerTest {

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=439266&siteId=1