我该如何测试Servlet过滤器?

时间:2015-05-23 02:47:27

标签: java spring spring-mvc spring-boot servlet-filters

无法弄清楚如何测试我的servlet过滤器

@Component
@Order( Ordered.HIGHEST_PRECEDENCE )
class CORSFilter extends OncePerRequestFilter {
    private final Logger log = LoggerFactory.getLogger( CORSFilter.class );

    @Override
    protected void doFilterInternal(
            final HttpServletRequest request,
            final HttpServletResponse response,
            final FilterChain filterChain )
            throws ServletException, IOException {
        log.debug( "request: {}", request );
        response.setHeader( "Access-Control-Allow-Origin", "*" );
        response.setHeader( "Access-Control-Allow-", "POST, GET, PUT, OPTIONS, DELETE" );
        response.setHeader( "Access-Control-Allow-Headers", "content-type, x-auth-token, x-requested-with" );
        response.setHeader( "Access-Control-Expose-Headers", "Location" );
        response.setIntHeader( "Access-Control-Max-Age", 3600 );
        filterChain.doFilter( request, response );
    }
}

这是我尝试编写测试的方法

@RunWith( SpringJUnit4ClassRunner.class )
@WebAppConfiguration
@ComponentScan( "com.xenoterracide.rpf.infrastructure.http")
@SpringApplicationConfiguration( classes = { MockServletContext.class } )
public class TestHeaders {

    @Autowired
    private WebApplicationContext context;
    private MockMvc               mockMvc;

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

    @Test
    public void testCORS() throws Exception {
        this.mockMvc.perform( options( "/" ) )
                    .andExpect( status().is2xxSuccessful() )
                    .andExpect( header().string( "Access-Control-Allow-Origin",
                            allOf( notNullValue(), instanceOf( String.class ) ) ) );
    }

}

这是我的测试错误

java.lang.AssertionError: Response header Access-Control-Allow-Origin
Expected: (not null and an instance of java.lang.String)
 but: not null was null

如何测试我的servlet过滤器是否正常运行?如果测试它们并不需要加载完整的上下文,db和all。

1 个答案:

答案 0 :(得分:8)

You can register a Filter instance in your MockMvc

this.mockMvc = MockMvcBuilders.webAppContextSetup( context )
                              .addFilter(new CORSFilter(), "/*")
                              .build();