how to write a junit test case for this class

Christine Shaji :

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;  
    }
}  
Torben :

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. :)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to write Junit test for this "FileNotFoundException"

How to write JUNIT test case for a class which implements ApplicationListener<ApplicationPreparedEvent>

How to write junit test for a java class that create object using new inside functions?

how to write Junit test case with an exception for below code?

How do I write a JUnit test case to test threads and events

How to write a jUnit test for a class that uses a network connection

how to write unit test case for controller class using mockito

How to test switch case in Junit using Mockito

How to write dynamic Test Case

How to write junit test case for thread run method

how to write junit test case to test outofmemory error

How to write Junit Test Case for KafkaStreams with Avro Deserializer and Avro Serializer

How to write a test case in Ballerina?

How to write junit test for DirectoryStream

How to write test case for string array input in junit?(new to junit)

How to write PowerMock test case?

How to write Junit test case for start method of consumer Verticle in vert.x?

Write Junit test case for Spring Retry max atttemps

How to make a test case as fail in Junit?

How Should I write JUnit test in the following case?

How to catch enwrapped exception in Junit test case?

How to write Junit test cases for a Thread class

How to perform @After for a specific JUnit test case?

How to write this test case?

How to write a test case for abstract class method

How to write Junit test case for spring boot:

How to write junit test case parsing jsonresponse?

How to write Junit test case array matrix addition and multiplication?

How to write a junit test for a scanner? (Reading a file)