How do I unit test a Servlet Filter with jUnit?

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

    ServletRequest, ServletResponse and FilterChain are all interfaces, so you can easily create test stubs for them, either by hand or using a mocking framework.

    Make the mock objects configurable so that you can prepare a canned response to getRequestURI() and so that you can query the ServletResponse to assert that sendRedirect has been invoked.

    Inject a mock ModeService.

    Invoke doFilter passing the mock ServletRequest, ServletResponse and FilterChain as its parameters.

    @Test
    public void testSomethingAboutDoFilter() {
        MyFilter filterUnderTest = new MyFilter();
        filterUnderTest.setModeService(new MockModeService(ModeService.ONLINE));
        MockFilterChain mockChain = new MockFilterChain();
        MockServletRequest req = new MockServletRequest("/maintenance.jsp");
        MockServletResponse rsp = new MockServletResponse();
    
        filterUnderTest.doFilter(req, rsp, mockChain);
    
        assertEquals("/maintenance.jsp",rsp.getLastRedirect());
    }
    

    In practice you'll want to move the setup into an @Before setUp() method, and write more @Test methods to cover every possible execution path.

    ... and you'd probably use a mocking framework like JMock or Mockito to create mocks, rather than the hypothetical MockModeService etc. I've used here.

    This is a unit testing approach, as opposed to an integration test. You are only exercising the unit under test (and the test code).

提交回复
热议问题