Skip to content

Instantly share code, notes, and snippets.

Embed
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.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
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;
@Before
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));
}
@Test
public void testPost1() throws Exception {
parameters.put("param1", "some value");
servlet.doPost(request, response);
assertThat(response_writer.toString(),
// a non-hamcrest core matcher
containsString("i'm only looking for this in the bloody long response"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment