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() {}
}
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)
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