Question

I am new to JUnit. I am trying to write a test case for java filter. Following is the filter code -

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException,
        IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type, Accept, authSessionId");
    }
    filterChain.doFilter(request, response);
}

Following is the testcase that I have written -

   @Test
   public void testSomethingAboutDoFilter() throws ServletException, IOException {
    CorsFilter cf = new CorsFilter();
    HttpServletRequest req = mock(HttpServletRequest.class);
    HttpServletResponse rsp = mock(HttpServletResponse.class);
    FilterChain mockChain = mock(FilterChain.class);
    rsp.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    when(req.getHeader("Access-Control-Request-Method")).thenReturn("abc");
    when(req.getMethod()).thenReturn("OPTIONS");
    cf.doFilterInternal(req, rsp, mockChain);
    String rspHeader = rsp.getHeader("Access-Control-Allow-Methods");
    System.out.println(rspHeader);
    }

The notion that I have in my mind is to check for what is added to the response and to match it to validate the test case. But for some reason I am getting null when I check -

   rsp.getHeader("Access-Control-Allow-Methods");

I tried finding out what could be the reason behind this and found that the header itself is not set. What should be the reason behind this and how can the test the code in that case.

Was it helpful?

Solution

rsp.addHeader is also a mocked method and values you set there are not returned via rsp.getHeader. But you can verify if methods on your mock object are invoked using verify method. If you really want to have addHeader to work together with getHeader, you should consider using a spy object that is backed by a real object. I would verify that addHeader was called with right arguments using verify(rsp).addHeader(...).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top