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
In Spring Boot 2, if we want our own security configuration, we can simply add a custom WebSecurityConfigurerAdapter. This will disable the default auto-configuration and enable our custom security configuration.
enabled=false and management. security. enabled=false should be set to disable the security.
One of the ways you can disable Spring Security filters in your tests, is to use the @AutoConfigureMockMvc annotation. @AutoConfigureMockMvc annotation can be applied to a test class to enable and configure auto-configuration of MockMvc.
For me in Spring Boot 2.2.4 (JUnit5) the below seems to have worked and bypass the security filter.
@ExtendWith(SpringExtension.class) @WebMvcTest(SomeController.class) @AutoConfigureMockMvc(addFilters = false) public class SomeControllerTest { ...
Note: this simply disables any filters in the SpringSecurity configuration. It won't disable the security completely. In other words it will still bootstrap security without loading any filters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With