Spring Boot 1.4 added @WebMvcTest that wire up the parts needed to do test a web slice of my application. This is fantastic, however I also want to ensure my custom filters and security code is wired up so I can validate that is working correctly too.
How can I add in custom filters when using @WebMvcTest?
@AutoConfigureWebMvc currently import the following auto-configuration classes (see spring.factories in the spring-boot-test-autoconfigure jar):
# AutoConfigureMockMvc auto-configuration imports
org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc=\
org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration,\
org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityAutoConfiguration,\
org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration,\
org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration
Out of this list MockMvcSecurityAutoConfiguration will automatically provide integration with the security filter.
If you need to add support for additional filters you can write your own MockMvcBuilderCustomizer (see MockMvcSecurityConfiguration.SecurityMockMvcBuilderCustomizer for inspiration).
You can either use nested @TestConfiguration class to hook your customizer into a specific test, you you could add your own spring.factories and use the AutoConfigureMockMvc key to automatically add it to all tests.
In addition to Spring Boot options @Phil Webb pointed out, you can use plain Spting Framework features and do something like this:
@Autowired
private WebApplicationContext context;
@Autowired
private FilterChainProxy springSecurityFilter;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.addFilters(springSecurityFilter)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
When using @WebMvcTest with Spring Security and a custom Filter, it will automatically be configured into the MockMvc instance. You can see this working in rwinch/spring-boot-sample/tree/so-38746850-webmvctest-customfilters. Specifically, the DemoApplicationTests demonstrates that Spring Security is properly setup and the custom filter is setup.
Spring Boot automatically adds all the Filters are setup using SpringBootMockMvcBuilderCustomizer.addFilters.
MockMvcSecurityConfiguration is used to setup Spring Security's testing support (i.e. Allows using @MockUser by adding Spring Security's SecurityMockMvcRequestPostProcessors.testSecurityContext() to the MockMvc instance.
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