Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unit test a Servlet Filter with jUnit? ServletRequest, ServletResponse, FilterChain

How to properly cover Filter with JUnit?

@SlingFilter(order = -700, scope = SlingFilterScope.REQUEST)
public class LoggingFilter implements Filter {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response,
            final FilterChain filterChain) throws IOException, ServletException {

        final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
        logger.debug("request for {}, with selector {}", slingRequest
                .getRequestPathInfo().getResourcePath(), slingRequest
                .getRequestPathInfo().getSelectorString());

        filterChain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}

}
like image 690
sam Avatar asked Mar 03 '23 02:03

sam


1 Answers

You can use below code for your testing with Junit-5

@ExtendWith(MockitoExtension.class)
public class LoggingFilterTest{
    
    @InjectMocks
    private LoggingFilter loggingFilter;
    
    @Mock
    private ServletRequest request
    
    @Mock
    private ServletResponse response
    
    @Mock
    private FilterChain filterChain
    
    @Mock
    private RequestPathInfo requestPathInfo;
    
    @Test
    public void testDoFilter() throws IOException, ServletException{
    
        Mockito.when(request.getResourcePath()).thenReturn(requestPathInfo);
        Mockito.when(requestPathInfo.getResourcePath()).thenReturn("/testPath", "selectorString");
        Mockito.doNothing().when(filterChain).doFilter(Mockito.eq(request), Mockito.eq(response));
        
        loggingFilter.doFilter(request, response, filterChain);
        
        Mockito.verify(filterChain, times(1)).doFilter(Mockito.eq(request), Mockito.eq(response));
    }
}

If you are using junit4 then change @ExtendWith(MockitoExtension.class) to @RunWith(MockitoJUnitRunner.class)

like image 186
SSK Avatar answered Apr 05 '23 23:04

SSK