[java] Junit test case for database insert method with DAO and web service

I am implementing a webservice based university management system. This system adds certain courses to database. here below is the code that I am using.

Course.java

public class Course {

    private String courseName;
    private String location;
    private String courseId;


       public String getCourseId()
               {
        return courseId;
            }

    public void setCourseId(String courseId) {
        this.courseId = courseId;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

        public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
}

then another file is as below

CourseDaoImpl.java

public class CourseDaoImpl implements IDao {
   Connection conn = null;
   Statement stmt = null;

public CourseDaoImpl(){

try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    conn = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/univesitydb", "root", "root");
    stmt = conn.createStatement();

    if (!conn.isClosed())
        System.out.println("Successfully connectiod");
} catch (SQLException e) {
    e.printStackTrace();
} catch (InstantiationException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}
}

      @Override
  public String add(Object object) {

Course c = (Course) object ;

String courseId = c.getCourseId();
String courseName = c.getCourseName();
String location = c.getLocation();

String result = "";
int rowcount;

try {
    String query = "Insert into course (courseId,courseName,location) values"
            + " ('"
            + courseId
            + "', '"
            + courseName
            + "', '"
            + location
            + "')";
    rowcount = stmt.executeUpdate(query);
    if (rowcount > 0) {
        result = "true";
        System.out.println("Course inserted successful");
    } else {
        result = "false:The data could not be inserted in the databse";
    }
} catch (SQLException e) {
    e.printStackTrace();
}

return result;
}

the third is the Web service file as follows which interacts with the previous two and adds data to database.

CourseService.java

package edu.service;

          import edu.dao.IDao;
          import edu.dao.impl.CourseDaoImpl;
          import edu.db.entity.Course;

       public class CourseService {

     public String addCourse(String courseId, String courseName, String location)
    {   
       Course c = new Course();
       c.setCourseId(courseId);
       c.setCourseName(courseName);
       c.setLocation(location);     
       IDao dao = new CourseDaoImpl();
       return dao.add(c);   
     }

Looking at my code listings can any body suggest me how do I write test case for my add method. I am totally beginner for JAVA, I took help from my friends to learn this java part and Now need to implement Junit test for my database methods like add course above.

Please suggest some thing that I can learn , read and use to implement Junit testing for my database methods.

This question is related to java web-services junit dao testcase

The answer is


The design of your classes will make it hard to test them. Using hardcoded connection strings or instantiating collaborators in your methods with new can be considered as test-antipatterns. Have a look at the DependencyInjection pattern. Frameworks like Spring might be of help here.

To have your DAO tested you need to have control over your database connection in your unit tests. So the first thing you would want to do is extract it out of your DAO into a class that you can either mock or point to a specific test database, which you can setup and inspect before and after your tests run.

A technical solution for testing db/DAO code might be dbunit. You can define your test data in a schema-less XML and let dbunit populate it in your test database. But you still have to wire everything up yourself. With Spring however you could use something like spring-test-dbunit which gives you lots of leverage and additional tooling.

As you call yourself a total beginner I suspect this is all very daunting. You should ask yourself if you really need to test your database code. If not you should at least refactor your code, so you can easily mock out all database access. For mocking in general, have a look at Mockito.


@Test
public void testSearchManagementStaff() throws SQLException
{
    boolean res=true;
    ManagementDaoImp mdi=new ManagementDaoImp();
    boolean b=mdi.searchManagementStaff("[email protected]"," 123456");
    assertEquals(res,b);
}

/*

public class UserDAO {

public boolean insertUser(UserBean u) {
    boolean flag = false;
    MySqlConnection msq = new MySqlConnection();
    try {

        String sql = "insert into regis values(?,?,?,?,?)";

        Connection connection = msq.getConnection();
        PreparedStatement statement = null;
        statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, u.getname());
        statement.setString(2, u.getlname());
        statement.setString(3, u.getemail());
        statement.setString(4, u.getusername());
        statement.setString(5, u.getpasswords());
        statement.executeUpdate();

        flag = true;
    } catch (Exception e) {
    } finally {
        return flag;
    }

}

public String userValidate(UserBean u) {
    String login = "";
    MySqlConnection msq = new MySqlConnection();
    try {
        String email = u.getemail();
        String Pass = u.getpasswords();

        String sql = "SELECT name FROM regis WHERE email=? and passwords=?";
        com.mysql.jdbc.Connection connection = msq.getConnection();
        com.mysql.jdbc.PreparedStatement statement = null;
        ResultSet rs = null;
        statement = (com.mysql.jdbc.PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, email);
        statement.setString(2, Pass);
        rs = statement.executeQuery();
        if (rs.next()) {
            login = rs.getString("name");
        } else {
            login = "false";
        }

    } catch (Exception e) {
    } finally {
        return login;
    }
}

public boolean getmessage(UserBean u) {
    boolean flag = false;
    MySqlConnection msq = new MySqlConnection();
    try {


        String sql = "insert into feedback values(?,?)";

        Connection connection = msq.getConnection();
        PreparedStatement statement = null;
        statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, u.getemail());
        statement.setString(2, u.getfeedback());
        statement.executeUpdate();

        flag = true;
    } catch (Exception e) {
    } finally {
        return flag;
    }

}

public boolean insertOrder(cartbean u) {
    boolean flag = false;
    MySqlConnection msq = new MySqlConnection();
    try {

        String sql = "insert into cart (product_id, email, Tprice, quantity) values (?,?,2000,?)";

        Connection connection = msq.getConnection();
        PreparedStatement statement = null;
        statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, u.getpid());
        statement.setString(2, u.getemail());
        statement.setString(3, u.getquantity());

        statement.executeUpdate();

        flag = true;
    } catch (Exception e) {
        System.out.print("hi");
    } finally {
        return flag;
    }

}

}


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to web-services

How do I POST XML data to a webservice with Postman? How to send json data in POST request using C# org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? The request was rejected because no multipart boundary was found in springboot Generating Request/Response XML from a WSDL How to send a POST request using volley with string body? How to send post request to the below post method using postman rest client How to pass a JSON array as a parameter in URL Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Examples related to junit

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to resolve Unneccessary Stubbing exception JUnit 5: How to assert an exception is thrown? How do I mock a REST template exchange? Class Not Found: Empty Test Suite in IntelliJ Unable to find a @SpringBootConfiguration when doing a JpaTest Failed to load ApplicationContext (with annotation) Example of Mockito's argumentCaptor Mockito - NullpointerException when stubbing Method Spring jUnit Testing properties file

Examples related to dao

Data access object (DAO) in Java Junit test case for database insert method with DAO and web service Where does the @Transactional annotation belong?

Examples related to testcase

Junit test case for database insert method with DAO and web service