java - 如何为这个类编写一个junit测试用例

原文 标签 java unit-testing servlets junit mockito

更新

我正在尝试使用 Mockito 和 Junit 为以下代码编写测试用例。
请问我应该怎么写。
因为我是这种语言的新手,所以我对它不太了解。我已经为 PatientDao(正在通过)类编写了测试用例,但我不知道如何为 SaveServlet 执行此操作

为代码中的错误道歉。

注意* - 我没有使用任何框架。

保存 Servler.java

   package com.consentServlets;

    import java.io.IOException;
    import java.io.PrintWriter;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    @WebServlet("/SavePolicy")
    public class SavePolicy extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out=response.getWriter();
            //Getting the attributes from the UI
            String policy_Name = request.getParameter("policy_name");
            String organization_Name = request.getParameter("orgid");
            String start_Date=request.getParameter("sop");
            String end_Date = request.getParameter("eop");
            //Setting the objects to insert the achieved attributes to corresponding the columns of the table
            policy savePolicy = new policy();
            savePolicy.setPolicyName(policy_Name);
            savePolicy.setOrgName(organization_Name);
            savePolicy.setStartDate(start_Date);
            savePolicy.setEndDate(end_Date);


            out.print(" <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css\">");
            //calling the save function from the patientDao class to execute the query
            DataConnection ds = new DataConnection();
            int status=new policyDao(ds).add(savePolicy);
            if(status>0){
                out.print("<p>Policy added successfully!</p>");
                request.getRequestDispatcher("manage_policy.html").include(request, response);
            }else{
                out.println("Sorry! failed");
            }

            out.close();
        }

    }

PatientDao.java
package com.consentServlets;
import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List; 

import java.sql.SQLException;
import javax.sql.DataSource;


public class patientDao {
    public DataConnection ds;
    public patientDao(DataConnection ds) {
        this.ds = ds;
    }
    public int save(patient addPatient){  
        int status = 0;  
        //Inserting patient details from UI to Database
        try{                            
            Connection con = ds.getConnection();  
            System.out.println(addPatient.getLastName());
            PreparedStatement ps = con.prepareStatement(  
                    "insert into patient(last_name,first_name,gender,age,dob) values (?,?,?,?,?)");  
            ps.setString(1,addPatient.getLastName());  
            ps.setString(2,addPatient.getFirstName());  
            ps.setString(3,addPatient.getGender());  
            ps.setString(4,addPatient.getAge());
            ps.setString(5,addPatient.getDoB());

            status = ps.executeUpdate();
            System.out.println(status);
            con.close();  
        }catch (SQLException e) {
            throw  new RuntimeException(e);}


        return status;  
    }  

    // Fetching all the records from table
    public  List<patient> getAllPatients(){  
        List<patient> list = new ArrayList<patient>();  

        try{  
            Connection con = ds.getConnection();  
            PreparedStatement ps = con.prepareStatement("select * from patient");  
            ResultSet rs = ps.executeQuery();  
            while(rs.next()){  
                patient getAllPatients=new patient();  
                getAllPatients.setId(rs.getInt(1));  
                getAllPatients.setFirstName(rs.getString(3));  
                getAllPatients.setLastName(rs.getString(2));  
                getAllPatients.setGender(rs.getString(4));  
                getAllPatients.setAge(rs.getString(5));
                getAllPatients.setDoB(rs.getString(6));   
                list.add(getAllPatients);  
            }  
            con.close();  
        }catch(Exception e){e.printStackTrace();}  

        return list;  
    }  
}  

患者.java
package com.consentServlets;
import java.util.List;
//creating objects for patient class which will help to store the patient details
public class patient {  
    private int id;  
    private String first_Name,last_Name,gender,age,dob;  
    public int getId() {  
        return id;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
    public String getFirstName() {   
        return first_Name;  
    }  
    public void setFirstName(String first_Name) {  
        this.first_Name = first_Name;  
    }  
    public String getLastName() {  
        return last_Name;  
    }  
    public void setLastName(String last_Name) {  
        this.last_Name = last_Name;  
    }  
    public String getGender() {  
        return gender;  
    }  
    public void setGender(String Gender) {  
        this.gender = Gender;  
    }  
    public String getAge() {  
        return age;  
    }  
    public void setAge(String Age) {  
        this.age = Age;  
    }  
    public String getDoB() {  
        return dob;  
    }  
    public void setDoB(String DOB) {  
        this.dob = DOB;  
    }
}  

最佳答案

它会比它需要的更困难(或不可能),因为你没有遵循 SOLID principles .

首先,您需要将构造策略对象的代码从请求参数重构为单独的映射器类,并为该类编写单元测试。通过消除输入解析的额外责任,这使得该方法更易于测试。

其次,您需要使用依赖注入(inject)将 policyDao 对象提供给 SavePolicy 类。因为您的方法通过使用 new 创建对象来声明依赖项本身。 ,您没有任何方法可以在 mehod 和 policyDao 之间使用模拟替换它。 Oncve 您正在注入(inject)依赖项,用模拟替换实际实现是微不足道的。

第三个你需要关注Java naming conventions并将policy和policyDao重命名为Policy和PolicyDao,并将snake_case字段名称转换为properCamelCase。 :)

关于java - 如何为这个类编写一个junit测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59949822/

相关文章:

php - 流明/Laravel : Can't figure out how unittesting a json response works

java - 无法获取 servlet 设置的 jSTL requestScope 变量

java - 约束 View 干扰显示键盘

java - 构建器模式的抽象类

java - Java 中的 Curl oAuth 等效项

Java Junit 测试问题

javascript - 测试 React Modal 组件

java - 通过命令行运行Maven @Tests

java - 如何对使用 Part 类型参数的方法进行单元测试?

java - ServletException 还是 IOException?