Implemented doFilter()
. How to properly cover Filter with jUnit ?
public void doFilter(ServletRequest servletRequest, ServletResponse servletRes
If you are using Spring then it has own mocks:
For example, you can add headers and set test Uri.
So your test can be smth like this:
@RunWith(MockitoJUnitRunner.class)
public class TokenAuthenticationFilterTest {
private static final String token = "260bce87-6be9-4897-add7-b3b675952538";
private static final String testUri = "/testUri";
@Mock
private SecurityService securityService;
@InjectMocks
private TokenAuthenticationFilter tokenAuthenticationFilter = new TokenAuthenticationFilter();
@Test
public void testDoFilterInternalPositiveScenarioWhenTokenIsInHeader() throws ServletException, IOException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(TOKEN, token);
request.setRequestURI(testUri);
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
when(securityService.doesExistToken(token)).thenReturn(true);
tokenAuthenticationFilter.doFilterInternal(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
}
}