How do I unit test a Servlet Filter with jUnit?

前端 未结 3 1609
日久生厌
日久生厌 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:46

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

提交回复
热议问题