How can I use @WebMvcTest as well as add my own filters?

Spring @WebMvcTest downloading 1.4, add @WebMvcTest to include the components needed to test the web fragment of my application. This is fantastic, however I also want my custom filters and security code to be connected, so I can verify that this works too.

How to add custom filters when using @WebMvcTest ?

+6
source share
3 answers

@AutoConfigureWebMvc currently imports the following auto-configuration classes (see spring.factories in the spring-boot-test-autoconfigure bank):

 # 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 

From 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 use the @TestConfiguration nested class to bind your customizer to a specific test, you can add your own spring.factories and use the AutoConfigureMockMvc key to automatically add it to all tests.

+3
source

When using @WebMvcTest with Spring Security and a custom filter, it will be automatically configured for the MockMvc instance. You can see that this works in rwinch / spring-boot-sample / tree / so-38746850-webmvctest-customfilters . In particular, DemoApplicationTests demonstrates that Spring Security is configured correctly and that a custom filter is configured.

Spring Boot automatically adds all Filter settings using SpringBootMockMvcBuilderCustomizer.addFilters .

MockMvcSecurityConfiguration is used to configure Spring support for security testing (i.e. allows you to use @MockUser by adding Spring Security SecurityMockMvcRequestPostProcessors.testSecurityContext() to an instance of MockMvc .

+1
source

In addition to Spring, @Phil Webb boot options are noted, you can use the simple Spting Framework functions 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(); } 
0
source

All Articles