Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito servlet test: cannot use response - it's not committed

I've made a basic test for servlet to test it's response status code, but it doesn't work - it's always 0, although I've 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 let this work?

like image 548
WildDev Avatar asked May 08 '15 21:05

WildDev


2 Answers

You want to test this differently. You need to verify that your inputs caused the expected outputs. For non-mock results, you would assert the behavior. Since you want to verify that your outputs were set properly.

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 to not be touched given certain inputs, then you should consider verifying that behavior using verify(response, never()).shouldNotBeCalledButSometimesIs() (to verify when conditions control it being called/set versus not).

like image 200
pickypg Avatar answered Sep 19 '22 06:09

pickypg


You're mocking HttpServletResponse. So, since it's a mock, getStatus() will only return a non-zero value until you tell the mock to return something else when getStatus() is called. It won't return the value passed to setStatus(), which, since it's a mock, doesn't do anything.

You could use a "smarter" mock HttpServletResponse, like the one provided by Spring.

like image 28
JB Nizet Avatar answered Sep 21 '22 06:09

JB Nizet