Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在使用mockito测试httpServlet过滤器时,如何模拟静态映射?_Java_Unit Testing_Static_Mocking_Mockito - Fatal编程技术网

Java 在使用mockito测试httpServlet过滤器时,如何模拟静态映射?

Java 在使用mockito测试httpServlet过滤器时,如何模拟静态映射?,java,unit-testing,static,mocking,mockito,Java,Unit Testing,Static,Mocking,Mockito,我有以下资料: @WebFilter(filterName = "SessionFilter", urlPatterns = {"/*"}) public class SessionFilter implements Filter { protected static String timeAttribute = "time"; protected static Map<String, myStats> urlToTimeCounterMapping = new

我有以下资料:

@WebFilter(filterName = "SessionFilter", urlPatterns = {"/*"})
public class SessionFilter implements Filter {

    protected static  String timeAttribute = "time";
    protected static Map<String, myStats> urlToTimeCounterMapping = new ConcurrentHashMap<>(); //Thread safe
编辑:


doFilter
检查它是否是一个新的url,如果是,它将使用计数器++将其添加到映射中,否则它将更新现有url的计数器,而不是使用模拟,只需将映射设置为设置中需要的任何值即可。在这个实例中使用mock太过分了。

doFilter()的代码在哪里?地图的实际大小是多少?为什么映射首先是静态的?它是静态的,因为我无法将它传递给doFilter,它正在计算传递的URL数(因此我无法每次初始化它)。你是什么意思?我试着使用“when”和“theReturn”,但我得到了一个错误
@Test
public void testDoFilter() throws Exception {
    // 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
    SessionFilter Rlla = new SessionFilter();
    Object aa = new Date();

    when(httpServletRequest.getAttribute("time")).thenReturn(aa);

    Rlla.doFilter(httpServletRequest, httpServletResponse, filterChain);

    boolean a = false;
    if (Rlla.urlToTimeCounterMapping.size() == 1) {
        a = true;
    }

    assertEquals(true, a);
}