Implemented doFilter(). How to properly cover Filter with jUnit ?
public void doFilter(ServletRequest servletRequest, ServletResponse servletRes
You could use a mocking framework in order to mock the above HttpServletRequest, HttpServletResponse and FilterChain objects and their behavior. Depending on the framework, you have certain functionality in order to verify if during the execution of the code correct actions on the mocked objects where taken.
For example when using the Mockito mock framework, the provided doFilter() method could be JUnit tested using below test case:
@Test
public void testDoFilter() throws IOException, ServletException {
// create the objects to be mocked
HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
FilterChain filterChain = mock(FilterChain.class);
// mock the getRequestURI() response
when(httpServletRequest.getRequestURI()).thenReturn("/otherurl.jsp");
MaintenanceFilter maintenanceFilter = new MaintenanceFilter();
maintenanceFilter.doFilter(httpServletRequest, httpServletResponse,
filterChain);
// verify if a sendRedirect() was performed with the expected value
verify(httpServletResponse).sendRedirect("/maintenance.jsp");
}