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)向 SavePolicy 类提供policyDao 对象。因为您的方法通过使用 new 创建对象来声明依赖关系本身,所以您没有任何方法可以进入 mehod 和policyDao 之间以将其替换为模拟。一旦您注入(inject)了依赖项,用模拟替换实际的实现就很简单了。

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

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

相关文章:

java - 从 Servlet 发送 JSon 对象的最佳方式

Python模拟异常没有被捕获

ios - 如何在 Xcode 6 上对应用程序扩展进行单元测试

java - Servlet 中的线程和并发

java - (Java/Spring)什么是 ".from()"? (与示例一起使用)

java - hibernate 搜索。如何从索引中排除实体?

java - 格式化 TextWatcher android

java - Jenkins Slave 使用JNLP 需要安全提示

c# - 我的类(class)有 30 个属性,单元测试很痛苦不是吗?

java - 如何创建多个异步 java 过滤器?