How do I unit test a Servlet Filter with jUnit?

前端 未结 3 1606
日久生厌
日久生厌 2020-12-08 19:03

Implemented doFilter(). How to properly cover Filter with jUnit ?

public void doFilter(ServletRequest servletRequest, ServletResponse servletRes         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 19:56

    If you are using Spring then it has own mocks:

    • org.springframework.mock.web.MockFilterChain
    • org.springframework.mock.web.MockHttpServletRequest
    • org.springframework.mock.web.MockHttpServletResponse

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

提交回复
热议问题