我遇到了测试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过滤器是否正常工作?如果测试不需要加载整个上下文、数据库等,则获得额外的积分。