我正在实施基于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测试。
答案 0 :(得分:16)
这是在spring项目中使用junit的一个示例dao测试。
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;
}
}
答案 1 :(得分:5)
您的课程设计将难以测试它们。使用硬编码连接字符串或使用new
在方法中实例化协作者可以被视为测试反模式。看看DependencyInjection模式。像Spring这样的框架在这里可能会有所帮助。
要对DAO进行测试,您需要在单元测试中控制数据库连接。因此,您要做的第一件事就是将它从DAO中提取到一个类中,您可以模拟或指向特定的测试数据库,您可以在测试运行之前和之后设置和检查它。
测试db / DAO代码的技术解决方案可能是dbunit。您可以在无模式XML中定义测试数据,并让dbunit在测试数据库中填充它。但你仍然需要自己连接所有东西。但是使用Spring,你可以使用像spring-test-dbunit这样的东西,它可以为你提供很多杠杆和额外的工具。
当你称自己为初学者时,我怀疑这一切都非常令人生畏。您应该问问自己是否真的需要测试数据库代码。如果不是,您至少应该重构代码,这样您就可以轻松模拟所有数据库访问。对于一般的模拟,请查看Mockito。
答案 2 :(得分:2)
@Test
public void testSearchManagementStaff() throws SQLException
{
boolean res=true;
ManagementDaoImp mdi=new ManagementDaoImp();
boolean b=mdi.searchManagementStaff("vinitk95@gmail.com"," 123456");
assertEquals(res,b);
}
答案 3 :(得分:-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;
}
}
}