java - 如何测试使用数据库登录的Servlet?

标签 java unit-testing junit mockito jmockit

大家好,我想使用 mocκito 或 JUNIT 测试此代码。

//登录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);
        }




}

}

如果在数据库中找到用户,则 user.authenticate 方法返回 true。 log.log(记录用户的IP地址以及成功或失败) 谁能帮我测试一下。

最佳答案

无法对涉及数据库交互的代码进行单元测试。这些都包含在集成测试中。但是,如果您想在 JUnit 测试下测试它,那么您可以模拟连接并返回值来测试场景,使用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

}

也不要忘记以同样的方式模拟上下文。

关于java - 如何测试使用数据库登录的Servlet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32147539/

相关文章:

java - Service在Thread.sleep后接收命令

java - 正则表达式匹配 [任何字符][任何数字]点与异常情况

python - 如何在 python 中为变量赋值编写单元测试?

java - JUnit 4 与 TestNG 6

java - JUnit 4.x : why is @Before never executed?

java - 如何在 Eclipse 中为 Guava 的 ArrayListMultiMap 类创建 JUnit 测试用例?

java - 比较两个字符串与 "==": when will it work?

java - 如何在 Java 中快速将整个目录的文本文件读入内存?

javascript - 我们可以在 Angular 中使用 Jasmine/Karma 测试 ngrx 流吗?

unit-testing - 如何对 CLI 输出进行单元测试