【发布时间】:2016-01-26 17:59:18
【问题描述】:
我有以下几点:
@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 时,我将一个对象添加到地图中。所以在测试我的班级时,我希望urlToTimeCounterMapping 的大小为1。问题是它是静态的,我得到null。有什么办法可以吗?
这是我的测试:
@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);
}
编辑:
doFilter 检查它是否是一个新的 url,如果是 - 它将使用 counter++ 将其添加到地图中,否则 - 它会更新现有 url 的计数器
【问题讨论】:
-
doFilter()的代码在哪里?地图的实际大小是多少?为什么地图首先是静态的?
-
它是静态的,因为我不能将它传递给 doFilter 并且它正在计算通过的 url 的数量(所以我不能每次都初始化它......)。
标签: java unit-testing static mocking mockito