mardi 26 janvier 2016

How to mock static map when testing httpServlet Filter using mockito?

I have the following:

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

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

When I use doFilter, I add an object to the map. So when testing my class, I expect urlToTimeCounterMapping size to be 1. The problem is that it's static and I get null. Is there a way I can do it?

this is my test:

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


    }

Aucun commentaire:

Enregistrer un commentaire