使用MockMvc的自定义Spring Security筛选器测试始终返回404

时间:2019-06-26 17:18:46

标签: spring-boot spring-security mockmvc

我正在尝试使用MockMvc测试自定义过滤器,它始终返回状态404,而不是从过滤器类返回的实际状态。 过滤器类如下所示:

    public class CustomFilter extends GenericFilterBean {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {

            HttpServletRequest request = (HttpServletRequest) servletRequest;
            // some logic 
            chain.doFilter(servletRequest, servletResponse);
        }
    }

已使用SpringBootApplicationFilterRegistrationBean中注册了

    @SpringBootApplication
    public class MyApplication {

        public static void main(String[] args) {
           try {
              ConfigurableApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
           } catch (Throwable e) {
        }

        @Bean
        public FilterRegistrationBean<CustomFilter> customFilter() {
           FilterRegistrationBean<CustomFilter> filterRegistration = new FilterRegistrationBean<>();
           filterRegistration.setFilter(new CustomFilter());
           filterRegistration.addUrlPatterns("/test/*");
           return filterRegistration;
        }
    }

为此编写的测试如下:

    @RunWith(SpringRunner.class)
    @SpringBootTest(CustomFilter.class)
    @EnableAutoConfiguration 
    @WebAppConfiguration
    public class CustomFilterTest {

        @Autowired
        private CustomFilter filter;

        @Autowired
        private WebApplicationContext context;

        private MockMvc mvc;

        @Before
        public void setup() {
            this.mvc = MockMvcBuilders.webAppContextSetup(context)
                 .addFilters(filter)
                 .build();
        }

        @Test
        public void testCustomFilter() throws Throwable {

           MockHttpServletRequestBuilder request = MockMvcRequestBuilders
                .request(HttpMethod.POST, "/resource/abc")
                .header("SomeHeader", "xxx")
                .content("{}");

           MockHttpServletResponse response = mvc.perform(request).andReturn().getResponse();

           assertEquals(response.getStatus(), HttpServletResponse.SC_CONTINUE);
        }
    }

断言始终返回状态值404。

我在这里想念东西吗?

1 个答案:

答案 0 :(得分:0)

将urlPatterns添加到addFilter(filter, "/resource/abc")并为上述代码段添加测试控制器,如下所示:

@RestController
public class TestController {

    @PostMapping("/resource/abc")
    public void testSecureEndpoint() {

    }
}