title: How to test my servlet using JUnit
body: <p>I have created a web system using Java Servlets and now want to make JUnit testing. My <code>dataManager</code> is just a basic piece of code that submits it to the database. How would you test a Servlet with JUnit?</p>
  
  <p>My code example that allows a user to register/sign up, which is submitted from my main page via AJAX:</p>
  
  <pre><code>public void doPost(HttpServletRequest request, HttpServletResponse response) 
           throws ServletException, IOException{
  
      // Get parameters
      String userName = request.getParameter("username");
      String password = request.getParameter("password");
      String name = request.getParameter("name");
  
      try {
  
          // Load the database driver
          Class.forName("com.mysql.jdbc.Driver");
  
          //pass reg details to datamanager       
          dataManager = new DataManager();
          //store result as string
          String result = dataManager.register(userName, password, name);
  
          //set response to html + no cache
          response.setContentType("text/html");
          response.setHeader("Cache-Control", "no-cache");
          //send response with register result
          response.getWriter().write(result);
  
      } catch(Exception e){
          System.out.println("Exception is :" + e);
      }  
  }
  </code></pre>