简体   繁体   中英

how to write a junit test case for this class

UPDATED

I am trying to write a test case for the following code using Mockito and Junit.. May I know how should i write it. As i am new to this language i don't have much idea about it. I have coded test case for patientDao(which is passing) class but i dont know how to do it for SaveServlet

Apologizing for the mistakes in the code.

Note* - I am not using any frameworks.

Save 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;  
    }  
}  

patient.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;  
    }
}  

Its going to be more difficult (or impossible) than it needs to be, because you are not following the SOLID principles .

First you need to refactor the code that constructs the policy object from the request parameters into a separate mapper class and write unit tests for that class. This makes the method easier to test by removing the additional responsibility of input parsing from it.

Second you need to provide the policyDao object to the SavePolicy class using dependency injection. Because your method declares the dependency itself by creating the object with new , you do not have any way for getting in between the mehod and policyDao to replace it with a mock. Oncve you are injecting the dependency, replacing the actual implementation with a mock is trivial.

Third you need to follow Java naming conventions and rename policy and policyDao to Policy and PolicyDao and covert the snake_case field names into properCamelCase. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM