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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With