写了一个测试类来作单位测试,
将日志打出来,发现它的执行顺序为:
setUp()
依次几个testMethod
tearDown()
我们可以在setUp声明初始化一些变量
注意每一个测试方法没用前都调用一次setUp()
在调用完testMethod后会调用一次tearDown。
根据上面代码,可以知道每一个测试方法执行后,都会提交事务,使之成为待久态
上面的测试模式可以作为一个模板。。。
public
class
TestUserDao
extends
TestCase
{
private static Log log = LogFactory.getLog(DaoFactory.class);
IUserDAO userDAO;
static String username = "test" + (int)(Math.random() * 100000);
static String userid;
protected void setUp() throws Exception{
super.setUp();
userDAO = (IUserDAO)DaoFactory.getDao("UserDAO");
this.assertNotNull("User dao is null..", userDAO);
HibernateSessionFactory.getSessionFactory().getCurrentSession().beginTransaction();
}
protected void tearDown() throws Exception{
super.tearDown();
HibernateSessionFactory.getSessionFactory().getCurrentSession().getTransaction().commit();
}
public void testSaveUser(){
Userinfo user = new Userinfo();
user.setName(this.username);
user.setPassword("test");
userDAO.saveUserInfo(user);
assertNotNull("save user success", user.getId());
userid = user.getId();
Userinfo u3 = new Userinfo();
u3.setName(this.username);
u3.setPassword("ttt");
boolean result = false;
try{
userDAO.saveUserInfo(u3);
}catch(BlogDAOException ex){
result = true;
}
assertTrue("ther userinfo not existes", result);
}
public void testGetUser(){
Userinfo user = userDAO.getUserInfo(username);
assertNotNull("Get user success!", user);
}
public void testGetUserById(){
Userinfo user = userDAO.getUserById(userid);
assertNotNull("get by id is success!", user);
}
}
private static Log log = LogFactory.getLog(DaoFactory.class);
IUserDAO userDAO;
static String username = "test" + (int)(Math.random() * 100000);
static String userid;
protected void setUp() throws Exception{
super.setUp();
userDAO = (IUserDAO)DaoFactory.getDao("UserDAO");
this.assertNotNull("User dao is null..", userDAO);
HibernateSessionFactory.getSessionFactory().getCurrentSession().beginTransaction();
}
protected void tearDown() throws Exception{
super.tearDown();
HibernateSessionFactory.getSessionFactory().getCurrentSession().getTransaction().commit();
}
public void testSaveUser(){
Userinfo user = new Userinfo();
user.setName(this.username);
user.setPassword("test");
userDAO.saveUserInfo(user);
assertNotNull("save user success", user.getId());
userid = user.getId();
Userinfo u3 = new Userinfo();
u3.setName(this.username);
u3.setPassword("ttt");
boolean result = false;
try{
userDAO.saveUserInfo(u3);
}catch(BlogDAOException ex){
result = true;
}
assertTrue("ther userinfo not existes", result);
}
public void testGetUser(){
Userinfo user = userDAO.getUserInfo(username);
assertNotNull("Get user success!", user);
}
public void testGetUserById(){
Userinfo user = userDAO.getUserById(userid);
assertNotNull("get by id is success!", user);
}
}
setUp()
依次几个testMethod
tearDown()
我们可以在setUp声明初始化一些变量
注意每一个测试方法没用前都调用一次setUp()
在调用完testMethod后会调用一次tearDown。
根据上面代码,可以知道每一个测试方法执行后,都会提交事务,使之成为待久态
上面的测试模式可以作为一个模板。。。