簡體   English   中英

如何為此類編寫junit測試用例

[英]how to write a junit test case for this class

更新

我正在嘗試使用 Mockito 和 Junit 為以下代碼編寫測試用例。 因為我是這種語言的新手,所以我對它不太了解。 我已經為 PatientDao(正在通過)類編寫了測試用例,但我不知道如何為 SaveServlet 編寫測試用例

為代碼中的錯誤道歉。

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

保存 Server.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();
        }

    }

病人道

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 原則

首先,您需要將根據請求參數構造策略對象的代碼重構為單獨的映射器類,並為該類編寫單元測試。 這通過從中刪除輸入解析的額外責任使方法更易於測試。

其次,您需要使用依賴注入向 SavePolicy 類提供 policyDao 對象。 因為您的方法通過使用new創建對象來聲明依賴項本身,所以您無法在 mehod 和 policyDao 之間使用模擬來替換它。 Oncve 您正在注入依賴項,用模擬替換實際實現是微不足道的。

第三,您需要遵循Java 命名約定並將policy 和policyDao 重命名為Policy 和PolicyDao,並將snake_case 字段名稱轉換為properCamelCase。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM