How can I use @WebMvcTest and also add in my own custom filters?

前端 未结 3 1389
遇见更好的自我
遇见更好的自我 2021-01-05 06:55

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 cu

相关标签:
3条回答
  • 2021-01-05 07:03

    @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.

    0 讨论(0)
  • 2021-01-05 07:08

    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();
    }
    
    0 讨论(0)
  • 2021-01-05 07:27

    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.

    0 讨论(0)
提交回复
热议问题