Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
[Java][GAE][Mockito] testing servlet requests/responses
import static org.junit.Assert.*;
import static org.junit.matchers.JUnitMatchers.*; // for non-hamcrest core matchers
import static org.mockito.Mockito.*;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class MyServletTest {
private MyServlet servlet;
private HttpServletRequest request;
private HttpServletResponse response;
private StringWriter response_writer;
private Map<String, String> parameters;
public void setUp() throws IOException {
parameters = new HashMap<String, String>();
servlet = new MyServlet();
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
response_writer = new StringWriter();
when(request.getParameter(anyString())).thenAnswer(new Answer<String>() {
public String answer(InvocationOnMock invocation) {
return parameters.get((String) invocation.getArguments()[0]);
when(response.getWriter()).thenReturn(new PrintWriter(response_writer));
public void testPost1() throws Exception {
parameters.put("param1", "some value");
servlet.doPost(request, response);
// a non-hamcrest core matcher
containsString("i'm only looking for this in the bloody long response"));

This comment has been minimized.

Copy link

@amalio amalio commented Mar 19, 2015

Thx!, very useful. I had to add:


to prevent NullPointerException

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment