Mockito Servlet Test: Cannot Use Response - It Fails

I ran a basic test for the servlet to check its response status code, but it doesn't work - it is always 0, although I set the response status code inside the servlet to 200.

public class TestMyServlet extends Mockito {

@Test
public void test() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);

    when(request.getParameter("test")).thenReturn("1");

    new MyServlet().doPost(request, response);

    System.out.println(response.isCommited()); // false
    System.out.println(response.getContentType()); // null
    System.out.println(response.getStatus()); // 0
  }
}

      

How to do it?

+3


source to share


2 answers


You are mocking HttpServletResponse. Thus, since it is a mock, it getStatus()

only returns a nonzero value, unless you tell the mock to return something else when called getStatus()

. It will not return the value passed in setStatus()

, which, since it is a mock, does nothing.



You can use a "smarter" HttpServletResponse layout like the one provided by Spring .

+5


source


You want to test this in a different way. You must ensure that your inputs produce the expected results. For non-fake results, you assert the behavior. Because you want to check if your outputs are set correctly.

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class MyServletTests {
    @Test
    public void testValidRequest() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);
        HttpServletResponse response = mock(HttpServletResponse.class);

        when(request.getParameter("test")).thenReturn("1");

        new MyServlet().doPost(request, response);

        // ensure that the request was used as expected
        verify(request).getParameter("test");

        // ensure that the response was setup as expected based on the
        //  mocked inputs
        verify(response).setContentType("text/html");
        verify(response).setStatus(200);
    }
 }

      



If you expect something is not touched at certain inputs, then you should consider checking what behavior is using verify(response, never()).shouldNotBeCalledButSometimesIs()

(for checking when the control condition is called / set against).

+6


source







All Articles