having trouble figuring out how to test my servlet filters
@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 );
}
}
here's what I've tried writing test wise
@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 ) ) ) );
}
}
here's my test error
java.lang.AssertionError: Response header Access-Control-Allow-Origin
Expected: (not null and an instance of java.lang.String)
but: not null was null
how can I test that my servlet filters are functioning correctly? bonus points if testing them doesn't require loading the full context, db and all.
You can register a Filter
instance in your MockMvc
this.mockMvc = MockMvcBuilders.webAppContextSetup( context )
.addFilter(new CORSFilter(), "/*")
.build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With