如何 Junit 测试具有特定响应的 servlet 过滤器

hb5*_*5fa 3 testing junit servlets mockito servlet-filters

对这段代码进行单元测试的最佳方法是什么?我需要对 httpResponse 建立一致的检查,当条件为真时,其 sendError() 。提前致谢!

编辑:不幸的是,这个过滤器不适用于 Spring MVC,所以我的选择是有限的。

    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);
}
Run Code Online (Sandbox Code Playgroud)

Cod*_*und 6

例如,当使用Mockito模拟框架时,doFilter()可以使用以下测试用例对提供的方法进行 JUnit 测试:

@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!");
}
Run Code Online (Sandbox Code Playgroud)