Disable Spring Security Configuration for @WebMvcTest

In this blog post, you will learn a couple of ways you can disable Spring Security Configuration for your @WebMvcTest.

Disable Security Filters for @AutoConfigureMockMvc

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.

To exclude security filters in your MockMvc tests, set the addFilters property to false.

@WebMvcTest
@AutoConfigureMockMvc(addFilters = false)
public class UsersControllerWebLayerTest {

}

@MockMvcTest – excludeAutoConfiguration

Another way to exclude Spring Security filters when doing integration testing with MockMvc is to use the excludeAutoConfiguration property with @MockMvcTest annotation.

To exclude Spring Security configuration configuration, exclude the SecurityAutoConfiguration.class.

@WebMvcTest(controllers = UsersController.class, excludeAutoConfiguration = {SecurityAutoConfiguration.class})
public class UsersControllerWebLayerTest {

 // Some code

}

Video lessons

I hope this tutorial was helpful to you. If you like learning by watching a series of step-by-step video lessons then have a look at my video course called “Testing Java with JUnit and Mockito“. This video course is for absolute beginners and you do not need to have any prior knowledge of testing Java applications to enrol.

Otherwise, if you’re eager to become proficient in testing Spring Boot applications, make sure to visit the Testing Java Code page. There, you’ll find a range of tutorials that cover various aspects of testing Spring Boot applications, equipping you with the knowledge to create reliable and high-quality software.

Happy learning!