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