Want to test my servlet using JUnit? You can do this using Mockito to have the mock return the correct params, verify they were indeed called (optionally specify number of times), write the ‘result’ and verify it’s correct.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.io.*; import javax.servlet.http.*; import org.apache.commons.io.FileUtils; import org.junit.Test; public class TestMyServlet extends Mockito{ @Test public void testServlet() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getParameter("username")).thenReturn("me"); when(request.getParameter("password")).thenReturn("secret"); StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); when(response.getWriter()).thenReturn(writer); new MyServlet().doPost(request, response); // only if you want to verify username was called... verify(request, atLeast(1)).getParameter("username"); writer.flush(); // it may not have been flushed yet... assertTrue(stringWriter.toString().contains("My expected string")); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.