【问题标题】:How to mock static map when testing httpServlet Filter using mockito?使用mockito测试httpServlet过滤器时如何模拟静态地图?
【发布时间】: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


【解决方案1】:

与其使用模拟,只需将地图设置为设置中所需的任何值。在这种情况下使用模拟只是大材小用。

【讨论】:

  • 什么意思?我尝试使用“when”和“theReturn”,但出现错误
猜你喜欢
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 2021-11-26
  • 2014-08-30
  • 2014-02-02
相关资源
最近更新 更多