title: How can you test the void doGet and doPost methods in a servlet with a JUnit test?
body: <p>I've written a servlet class and I would like to test the methods in this class. Unfortunately I'm having trouble with writing a good JUnit test for the doGet and doPost method in my servlet. What makes it hard for me is that these methods are void methods. So there is no expected outcome but they are definitely doing something.</p>
  
  <p>I've tried several variations but they didn't succeed. I get a NullPointerException when I'm testing. Can someone help me out?</p>
  
  <p>My Servlet</p>
  
  <pre class="lang-java prettyprint-override"><code>@WebServlet(name = "SearchContactServlet", urlPatterns = { "/SCFH", "/searchUser" })
  public class SearchContactServlet extends HttpServlet {
  
      /**
       * 
       */
      private static final long serialVersionUID = 1L;
  
      public SearchContactServlet() {
          super();
      }
  
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
  
          if (!SecurityTool.checkLogin(request, response)) {
              return;
          }
  
          String dispatchUrl = null;
          request.setAttribute("originalURI", request.getRequestURI());
          String action = getActionString(request);
  
          switch (action) {
          case "SCFH":
              dispatchUrl = "/jsp/searchContact.jsp";
              break;
          default:
              dispatchUrl = "/index.jsp";
              break;
  
          }
          if (dispatchUrl != null) {
              RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF" + dispatchUrl);
              rd.forward(request, response);
          }
      }
  
      @Override
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
  
          SecurityTool.checkLogin(request, response);
          if (!SecurityTool.checkLogin(request, response)) {
              return;
          }
  
          String dispatchUrl = null;
          request.setAttribute("originalURI", request.getRequestURI());
          String action = getActionString(request);
          String firstName = request.getParameter("firstname");
          String prefix = request.getParameter("prefix");
          String lastName = request.getParameter("lastname");
          String domain = request.getParameter("domain");
          String companyName = request.getParameter("companyname");
  
          Map&lt;String, String&gt; errors = new HashMap&lt;String, String&gt;();
  
          if (nullOrEmpty(firstName)) {
              errors.put("firstname", "Oops, something went wrong. Please enter a first name.");
              request.setAttribute("errors", errors);
              request.getRequestDispatcher("/WEB-INF" + "/jsp/searchContact.jsp").forward(request, response);
  
          } else if (nullOrEmpty(lastName)) {
              errors.put("lastname", "Oops, something went wrong. Please enter a last name.");
              request.setAttribute("errors", errors);
              request.getRequestDispatcher("/WEB-INF" + "/jsp/searchContact.jsp").forward(request, response);
  
          } else if (nullOrEmpty(domain)) {
              errors.put("domain", "Oops, something went wrong. Please enter a domain.");
              request.setAttribute("errors", errors);
              request.getRequestDispatcher("/WEB-INF" + "/jsp/searchContact.jsp").forward(request, response);
  
          }
  
          switch (action) {
          case "searchUser":
              PunchCard punchCard = new PunchCard(firstName, prefix, lastName, domain, companyName);
  //          Controller controller = new Controller();
              punchCard = Controller.getMail(punchCard);
              SearchResult[] searchResults = punchCard.getSearchResults();
              System.out.println("number of searchresults:" + punchCard.getSearchResults().length);
  
              // if (nullOrEmpty(firstName) || nullOrEmpty(lastName) || nullOrEmpty(domain)
              // || nullOrEmpty(companyName)) {
              // // Iets in het scherm printen dat bepaalde velden ingevuld moeten worden
              // Terug naar searchContact.jsp met boodschap "xxx moet worden ingevuld"
              // }
  
  
              request.setAttribute("punchCard", punchCard);
              request.setAttribute("searchResults", searchResults);
              dispatchUrl = "/jsp/result.jsp";
              break;
  
          default:
              dispatchUrl = "index.jsp";
              break;
  
          }
          if (dispatchUrl != null) {
              RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF" + dispatchUrl);
              rd.forward(request, response);
          }
      }
  </code></pre>
  
  <p>My JUnit test</p>
  
  <pre class="lang-java prettyprint-override"><code>@Test
      public void testServlet() {
          HttpServletRequest request = mock(HttpServletRequest.class);
          HttpServletResponse response = mock(HttpServletResponse.class);
  
          when(request.getParameter("firstName")).thenReturn("Piet");
          when(request.getParameter("prefix")).thenReturn("de");
          when(request.getParameter("lastName")).thenReturn("Vries");
          when(request.getParameter("domain")).thenReturn("springprofessional.nl");
          when(request.getParameter("companyName")).thenReturn("Spring");
  
          StringWriter stringWriter = new StringWriter();
          PrintWriter printWriter = new PrintWriter(stringWriter);
          try {
              when(response.getWriter()).thenReturn(printWriter);
          } catch (IOException e1) {
              e1.printStackTrace();
          }
  
          try {
              new SearchContactServlet().doPost(request, response);
          } catch (ServletException | IOException e) {
              e.printStackTrace();
          }
  
          printWriter.flush();
          assertTrue(stringWriter.toString().contains("Piet" + "de" + "Vries" + "springprofessional.nl" + "Spring"));
      }
  </code></pre>
  
  <p>This is the stacktrace:</p>
  
  <pre><code>java.lang.NullPointerException
  at nl.springprofessional.it.addressinatorWebApp.security.SecurityTool.checkLogin(SecurityTool.java:49)
  at nl.springprofessional.it.addressinatorWebApp.webServlet.SearchContactServlet.doPost(SearchContactServlet.java:68)
  at nl.springprofessional.it.addressinatorWebApp.webServlet.SearchContactServletTest.testServlet(SearchContactServletTest.java:41)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  at java.lang.reflect.Method.invoke(Unknown Source)
  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
  at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
  at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
  </code></pre>