How to Junit test servlet filter which has specific response

12,640

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 getRemoteAddr() response
    when(httpServletRequest.getRemoteAddr()).thenReturn("198.252.206.16");

    AccessFilter accessFilter = new AccessFilter();
    accessFilter.doFilter(httpServletRequest, httpServletResponse,
            filterChain);

    // verify if a sendError() was performed with the expected values
    verify(httpServletResponse).sendError(HttpServletResponse.SC_FORBIDDEN,
            "You are not allowed to access the server!");
}
Share:
12,640

Related videos on Youtube

hb5fa
Author by

hb5fa

Updated on September 15, 2022

Comments

  • hb5fa
    hb5fa over 1 year

    What is the best way to unit test this code? I need to establish a consistent check for httpResponse which sendError() when condition is true. Thanks in advance!

    Edit: Unfortunately, this filter is not with Spring MVC so my choice is limited.

        public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterchain) throws IOException, ServletException {
    
        String ipAddress = request.getRemoteAddr();
        if( SomeParameterCheckingFunction ((request)) ) {
            logger.error("Error detected! Time: " + new Date().toString() + ", Originating IP: " + ipAddress);
            if (response instanceof HttpServletResponse){
                HttpServletResponse httpResponse = (HttpServletResponse) response;
                httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,"You are not allowed to access the server!");
            }
        }
        filterchain.doFilter(request, response);
    }
    
  • hb5fa
    hb5fa over 11 years
    I already have another unit test against the SomeParameterCheckingFunction() so I can easily mock it with Mockito. Having the ability to verify response.sendError() will be an ideal test case but I am completely stumped on how to do that. Can you show me the technique on how I might be able to verify response.sendError() in junit after the filter is called? Tnx!