Search code examples
javaunit-testingjunitmockitojmockit

How to Test Servlet that uses database to login?


Hello guys i want to test this code using mocκito or JUNIT.

//Login Servlet

 @WebServlet("/login_controller")
public class login_controller extends HttpServlet {
private static final long serialVersionUID = 1L;

    private String  TAG="Login controller : ";
    private DataSource dataSource;
    private Connection connection;


    public void init() throws ServletException {
        connection=null;
        try {
            // Get DataSource
            Context initContext  = new InitialContext();
            Context envContext  = (Context)initContext.lookup("java:/comp/env");
            dataSource = (DataSource)envContext.lookup("jdbc/db");


        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

/**
 * @see HttpServlet#HttpServlet()
 */
public login_controller() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doPost(request,response);
//  response.getWriter().append("Served at: ").append(request.getContextPath());
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
//  doGet(request, response);
     response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String userName=null;
    String password=null;
    boolean user_found= false;

    //Get parameters From HTTP request
    userName = request.getParameter("username");
    password = request.getParameter("password");


    if(userName == null || password ==null ||userName.equals("")||password.equals("")){
        System.out.println(TAG + "Username or Password =  Empty strings");
        RequestDispatcher rs = request.getRequestDispatcher("index.jsp");
           rs.forward(request, response);
           return;

    }
    System.out.println(TAG+"Username :" + userName+ "\t Password :"+password);
    System.out.println(TAG+"Remote IP address is " + request.getRemoteAddr());

    //Log USER loggin attempt
    LOG_IP_USER log =new LOG_IP_USER();
    USERS_DB user   =new USERS_DB();


    try {
        connection = dataSource.getConnection();
        user_found=user.authenticate(connection, userName, password);

    }
    catch (NoSuchAlgorithmException | SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    finally
      {
          try { if(null!=connection)connection.close();} catch (SQLException e) 
          {e.printStackTrace();}
      }


      if(user_found)//User found in the database
        {
          log.log(request.getRemoteAddr(),userName,true);  
          System.out.println(TAG + "Username"+userName);

           Cookie userNameCookie=new Cookie("username",userName);
            userNameCookie.setMaxAge(60*15);//15 minutes
            response.addCookie(userNameCookie);
            response.sendRedirect("userChoice.jsp"); 
            return;
        }
        else
        {   
            log.log(request.getRemoteAddr(),userName,false);
            out.println ("<script>alert('Invalid Username Or Password!');</script>");
           RequestDispatcher rs = request.getRequestDispatcher("index.jsp");
           rs.include(request, response);
        }




}

}

The method user.authenticate returns true if the user is found in the database. log.log (logs the ip address of the user and success or fail ) Can anyone help me with testing.


Solution

  • Unit Testing can't be done on codes which involves database interactions.Those are covered in integration tests.However,if you want to test this under JUnit testing then You can mock the connection and return the values to test the scenarios using JMockit/Mockito.

    //sample code using JMockit
    @Test
    public void testMyMethod(@Mocked final USERS_DB user){
    
    new Expectations(){
                 {
                  user.authenticate(connection, userName, password);
                  result = true/false/Exception();
                }};
    //call method now to test
    
    }
    

    Also dont forget to mock the Context in the same way as well.