Issue
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
Solution
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 {
Note by the author: As of 2021, this answer has been obsolete for a few years and it probably won't work for you.
Answered By - Mzzl
Answer Checked By - Candace Johnson (JavaFixing Volunteer)