JUnit测试案例与DAO和Web服务数据库插入方法(Junit test case for dat

2019-09-01 07:20发布

我实现一个基于web服务的高校管理体系。 该系统增加了某些课程数据库。 这里下面是我使用的代码。

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

然后另一个文件是如下

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

第三是Web服务的文件,如下所示,其与前两交互,将数据添加到数据库中。

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

看着我的代码清单,任何机构可以建议我怎么做我写测试用例我的add方法。 我完全初学JAVA的,我帮助了我的朋友来学习这个Java部分,现在需要实现JUnit测试我的数据库的方法,如添加上述课程。

请提出了一些事情,我可以学习,阅读和使用来实现Junit的测试我的数据库的方法。

Answer 1:

这是春天项目使用JUnit一个样本道测试。

import java.util.List;

import junit.framework.Assert;

import org.jboss.tools.example.springmvc.domain.Member;
import org.jboss.tools.example.springmvc.repo.MemberDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-context.xml",
"classpath:/META-INF/spring/applicationContext.xml"})
@Transactional
@TransactionConfiguration(defaultRollback=true)
public class MemberDaoTest
{
    @Autowired
    private MemberDao memberDao;

    @Test
    public void testFindById()
    {
        Member member = memberDao.findById(0l);

        Assert.assertEquals("John Smith", member.getName());
        Assert.assertEquals("john.smith@mailinator.com", member.getEmail());
        Assert.assertEquals("2125551212", member.getPhoneNumber());
        return;
    }

    @Test
    public void testFindByEmail()
    {
        Member member = memberDao.findByEmail("john.smith@mailinator.com");

        Assert.assertEquals("John Smith", member.getName());
        Assert.assertEquals("john.smith@mailinator.com", member.getEmail());
        Assert.assertEquals("2125551212", member.getPhoneNumber());
        return;
    }

    @Test
    public void testRegister()
    {
        Member member = new Member();
        member.setEmail("jane.doe@mailinator.com");
        member.setName("Jane Doe");
        member.setPhoneNumber("2125552121");

        memberDao.register(member);
        Long id = member.getId();
        Assert.assertNotNull(id);

        Assert.assertEquals(2, memberDao.findAllOrderedByName().size());
        Member newMember = memberDao.findById(id);

        Assert.assertEquals("Jane Doe", newMember.getName());
        Assert.assertEquals("jane.doe@mailinator.com", newMember.getEmail());
        Assert.assertEquals("2125552121", newMember.getPhoneNumber());
        return;
    }

    @Test
    public void testFindAllOrderedByName()
    {
        Member member = new Member();
        member.setEmail("jane.doe@mailinator.com");
        member.setName("Jane Doe");
        member.setPhoneNumber("2125552121");
        memberDao.register(member);

        List<Member> members = memberDao.findAllOrderedByName();
        Assert.assertEquals(2, members.size());
        Member newMember = members.get(0);

        Assert.assertEquals("Jane Doe", newMember.getName());
        Assert.assertEquals("jane.doe@mailinator.com", newMember.getEmail());
        Assert.assertEquals("2125552121", newMember.getPhoneNumber());
        return;
    }
}


Answer 2:

你的类的设计将使它很难对它们进行测试。 使用硬编码的连接字符串或实例在你的方法协作者new可被视为测试反模式。 看一看在DependencyInjection模式。 像框架春天可能是帮助在这里。

为了使您的DAO测试,你需要有控制权在你的单元测试你的数据库连接。 所以,你会想要做的第一件事就是提取出来的DAO成一个类,您可以模拟或指向特定的测试数据库,你可以设置和之前和之后你的测试运行的检查。

测试DB / DAO代码的技术方案可能会DbUnit的 。 您可以在无模式的XML定义你的测试数据,让DbUnit的填充它在你的测试数据库。 但是你还是要连线了一切自己。 随着春天但是你可以使用类似弹簧试验的DbUnit ,让你大量的杠杆和额外的工具的。

当你说自己是初学者总我怀疑这是所有非常艰巨。 你应该问自己,如果你真的需要测试你的数据库代码。 如果不是你至少应该重构你的代码,这样你就可以很容易地模拟出所有数据库访问。 对于一般的嘲讽,看看的Mockito 。



Answer 3:

@Test
public void testSearchManagementStaff() throws SQLException
{
    boolean res=true;
    ManagementDaoImp mdi=new ManagementDaoImp();
    boolean b=mdi.searchManagementStaff("vinitk95@gmail.com"," 123456");
    assertEquals(res,b);
}


Answer 4:

/ *

公共类的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;
    }

}

}



文章来源: Junit test case for database insert method with DAO and web service