测试对一个Account的Dao操作以及Service。
- //先来测试最基本的dao吧
- package org.wuhua.dao;
- import java.util.Collection;
- public interface IBaseDao {
- Object save(Object o);
- void delete(Object o);
- Object update(Object o);
- Collection list();
- }
看下我的实现吧,采用Spring实现。
- package org.wuhua.dao.impl;
- import java.util.Collection;
- import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
- import org.wuhua.dao.IBaseDao;
- public class BaseDao extends HibernateDaoSupport
- implements IBaseDao {
- public void delete(Object o) {
- this.getHibernateTemplate().delete(o);
- }
- public Collection list() {
- return null;
- }
- public Object save(Object o) {
- return this.getHibernateTemplate().save(o);
- }
- public Object update(Object o) {
- this.getHibernateTemplate().update(o);
- return o;
- }
- }
- package org.wuhua.dao;
- import java.io.Serializable;
- import junit.framework.TestCase;
- import org.easymock.MockControl;
- import org.easymock.classextension.MockClassControl;
- import org.springframework.orm.hibernate3.HibernateTemplate;
- import org.wuhua.dao.impl.BaseDao;
- public class BaseDaoTest extends TestCase {
- MockControl control;
- private HibernateTemplate ht;
- private BaseDao baseDao;
- protected void setUp() throws Exception {
- control = MockClassControl.createControl(HibernateTemplate.class);
- ht = (HibernateTemplate) control.getMock();
- baseDao = new BaseDao();
- baseDao.setHibernateTemplate(ht);
- }
- public void testSave() {
- Object o = new Object();
- ht.save(o);
- //这里我是有疑问的。
- //1,为什么HibernateTemplate返回的是Serializable。
- //2,设置的返回植为什么一定要跟调用ht.save(o)一致呢?
- control.setReturnValue(new Wuhua());
- control.replay();
- baseDao.save(o);
- control.verify();
- }
- public void testUpdate() {
- Object a = new Object();
- ht.update(a);
- control.replay();
- try {
- baseDao.update(a);
- fail("Not catch exception!");
- } catch(Exception e) {
- }
- control.verify();
- }
- class Wuhua implements Serializable {}
- }
上面就是我第一次很认真的测试,有很多不明白的地方
里面对于测试Service大家是没有意义的,对于测试DAO层则表现各有各的看法。
比如
测试DAO不如连数据库一起测试吧。因为DAO测试的目的不是DAO接口实现对不对,而是测试是否如你预期的发送了SQL,如你预期的返回了结果集。这个时候你Mock之后,测试就没有意义了。
但对于mock来说是有莫大好处的。
比如service测试的时候完全可以做到隔离数据库,
我现在的意思是,
居然Service可以隔离Dao层,也就是说Dao层也是可以做到隔离相关的数据实现的。也是可以mock一个对象。而并非用实际的连接去代 替。如果我们的逻辑没出错的话,测试就算通过了,至于数据层的检测,那就不关我们的事情了,比如Hibernate由Hibernate去test, Spring由Spring去Test,Oracle由它自己去做。干自己的事情,别趟其他浑水。这样不是潇洒很多吗
但是数据库的测试毕竟比较特殊,记住测试的目的是确保你的代码质量,如果你确定你的这样测就没问题了,那无话可说,否则就尽量多的测试。
事实上,最原始的单元测试(plain testcase)就是用来测方法,测业务逻辑的,如果有逻辑就测,没逻辑就不用测了,同样的道理,相信你不会去测一个bean的get/set方法吧。
记住你测试的目的和动机,如果你认为测试dao层是为了测你的逻辑(你确定你的dao的实现代码是否真的存在逻辑),那你就mock吧,但是,我 们更相信,我们测DAO层,更应该是测访问数据库的情况,你如连接,sql是否正确,sequence是否正确等,而这些你必须要真正的连接数据库,也因 此,我们一般都是直接访问数据库来测试的,当然,如果可能你可以采用内存库。
事实上,我们对dao的测试,一般都进行所谓的的集成单元测试。我认为,你应该确定好你的测试策略,然后在去采用相应的测试方法。我在目前的开发中就是采用这样的方式测的。
上面两个大哥都建议测试DAO的时候还是连接数据库为好。
但个人认为上面两个大哥的单元测试以非纯正的单元测试了,而是集成单元测试。
其实说白了,测试这东西只是为了项目更好,更快的完成。至于是否要求纯单元,或者是集成单元测试,则看各位的需要,如果觉得集成单元测试对项目有帮助,那就用吧,现在发现对这个已经没有明显的界限了。
不理会它了,现在回归到我们用户注册的例子。
- 1. public interface IAccountDao extends IBaseDao {
- 2. public Account findAccountById(String id);
- 3. public Account findAccounByName(String name);
- 4. }
实际实现代码
- package org.wuhua.dao.impl;
- import java.util.List;
- import org.wuhua.dao.IAccountDao;
- import org.wuhua.model.Account;
- public class AccountDao extends BaseDao implements IAccountDao {
- public Account findAccountById(String id) {
- return (Account) this.getHibernateTemplate().get(Account.class, id) ;
- }
- public Account findAccounByName(String name) {
- List l = this.getHibernateTemplate().find("from Account as a where a.name=?", name);
- if(l != null && l.size() >=1)
- return (Account) l.get(0);
- else
- return null;
- }
- }
- package org.wuhua.dao;
- import java.util.ArrayList;
- import java.util.List;
- import junit.framework.Assert;
- import junit.framework.TestCase;
- import org.easymock.MockControl;
- import org.easymock.classextension.MockClassControl;
- import org.springframework.orm.hibernate3.HibernateTemplate;
- import org.wuhua.dao.impl.AccountDao;
- import org.wuhua.model.Account;
- public class AccountDaoTest extends TestCase {
- private AccountDao accountDao;
- private org.springframework.orm.hibernate3.HibernateTemplate ht;
- private MockControl control;
- protected void setUp() throws Exception {
- control = MockClassControl.createControl(HibernateTemplate.class);
- ht = (HibernateTemplate) control.getMock();
- accountDao = new AccountDao();
- accountDao.setHibernateTemplate(ht);
- }
- protected void tearDown() throws Exception {
- }
- public void testFindAccountById(){
- Account a = new Account("wuhua");
- a.setId("10");
- ht.get(Account.class, a.getId());
- control.setReturnValue(a);
- control.replay();
- Account result = accountDao.findAccountById(a.getId());
- assertNotNull(result);
- Assert.assertEquals(a.getId(),result.getId());
- Assert.assertEquals(a, result);
- control.verify();
- }
- public void testFindAccountByName(){
- Account a = new Account("wuhua");
- ht.find("from Account as a where a.name=?", a.getName());
- List l = new ArrayList();
- l.add(a);
- control.setReturnValue(l);
- control.replay();
- Account result = accountDao.findAccounByName(a.getName());
- Assert.assertEquals(a.getId(),result.getId());
- Assert.assertEquals(a, result);
- control.verify();
- }
- }
测试Service,因为Service依赖的Dao, 所以只需Mock一个Dao即可。在这里我详细的介绍关于注册这个功能的测试
- public interface IAccountService extends IBaseService {
- Account findAccountById(String id);
- Account findAccounByName(String name);
- void regist(Account account) throws ObjectExistsException;
- }
注册功能的实现。
- public void regist(Account account) throws ObjectExistsException {
- if(accountDao.findAccounByName(account.getName()) != null)
- throw new ObjectExistsException("User's name is exists!");
- accountDao.save(account);
- }
测试代码
- protected void setUp() throws Exception {
- control = MockControl.createControl(IAccountDao.class);
- accountDao = (IAccountDao) control.getMock();
- as = new AccountService();
- as.setAccountDao(accountDao);
- }
- public void testFindAccountByName() {
- String name = "wuhua";
- accountDao.findAccounByName(name);
- Account a = new Account("wuhua");
- a.setId(name);
- control.setReturnValue(a);
- control.replay();
- Account at = as.findAccounByName(name);
- Assert.assertEquals(name, at.getId());
- Assert.assertEquals(a, at);
- control.verify();
- }
首先我们建立一个关键字查询,name="wuhua";
然后调用Dao的方法,
然后自定义返回一个自己预期的对象,
最后通过比较这个对象判断结果是否是自己想要的
Action的测试是比较辛苦的。因为它依赖与其他的环境(比如tomcat)。
在我的印象中,基于struts的测试是很麻烦的,因为对于execute方法,你必须mock两个对象进去。
还好。基于Webwork的测试相对简单些。
下面让我们来测试一个例子吧
- Account account;
- IAccountService accountService;
- public void setAccount(Account account) {
- this.account = account;
- }
- public void setAccountService(IAccountService accountService) {
- this.accountService = accountService;
- }
- public String regist() throws Exception {
- if(account == null) {
- account = new Account();
- return INPUT;
- }
- if(!validForm(account))
- return INPUT;
- try {
- accountService.regist(account);
- } catch (ObjectExistsException e) {
- e.printStackTrace();
- return INPUT;
- }
- return SUCCESS;
- }
- private boolean validForm(Account e) {
- if(e.getName() == null || e.getName().trim().equals(""))
- return false;
- if(e.getPassword() == null || e.getPassword().trim().equals(""))
- return false;
- return true;
- }
有经验的程序员见到上面的代码应该就知道怎么测试了。
我们只需setAccount,跟setAccountService即可,
而Account本身来讲就是是个po,所以可以自己new一个
AccountService则可以mock一个。真是太完美了,我太喜好mock,它总是给我惊喜
- package org.wuhua.action;
- import junit.framework.TestCase;
- import org.easymock.MockControl;
- import org.wuhua.exception.ObjectExistsException;
- import org.wuhua.model.Account;
- import org.wuhua.service.IAccountService;
- import sms.king.AccountManager;
- import com.opensymphony.xwork.Action;
- public class AccountActionTest extends TestCase {
- private MockControl control;
- IAccountService accountService;
- protected void setUp() throws Exception {
- control = MockControl.createControl(IAccountService.class);
- accountService = (IAccountService) control.getMock();
- }
- public void testRegistOk() throws Exception {
- Account employee = new Account("name");
- employee.setPassword("password");
- accountService.regist(employee);
- control.setVoidCallable(1);
- control.replay();
- AccountAction action = new AccountAction();
- action.setAccount(employee);
- action.setAccountService(accountService);
- assertEquals(Action.SUCCESS, action.regist());
- control.verify();
- }
- public void testRegistNameExists() throws Exception {
- Account employee = new Account("name");
- employee.setPassword("password");
- accountService.regist(employee);
- control.setThrowable(new ObjectExistsException(""));
- control.replay();
- AccountAction action = new AccountAction();
- action.setAccount(employee);
- action.setAccountService(accountService);
- assertEquals(Action.INPUT, action.regist());
- control.verify();
- }
- }
ok,一个测试的例子就好了。
对ACTION我一般都是不测试的,因为它仅仅是页面的跳转而不包含逻辑 |
struts的action测试最好用strutstestcase,不需要实现那么多东西了…… |
这几天要用存储过程跟jdbc来做个项目,想想也有好长一段时间没用过JDBC来做项目了。该复习复习了。
前阵子学了easymock,真好现在可以派上用场了。不过在测试的过程中还是遇到了不小问题,想来是自己基础不好的缘故。
这次不TDD了,太麻烦了。
先看看我们要测试的代码
- CallableStatementcstmt = null;
- try {
- cstmt = _conn.prepareCall("{call LUCK_LOAD_COMMON(?,?)}");
- cstmt.setString(1, "1");
- cstmt.registerOutParameter(2, java.sql.Types.VARCHAR);
- cstmt.executeUpdate();
- return cstmt.getString(2);
- } catch (Exception e) {
- GxDebug.logException(e);
- e.printStackTrace();
- return null;
- } finally {
- if (cstmt != null)
- try {
- cstmt.close();
- } catch (Exception e) {
- }
- }
好再看看我们的测试代码
- conn.prepareCall("{call LUCK_LOAD_COMMON(?,?)}");
- conControl.setReturnValue(cstmt);
- conControl.replay();
- cstmt.setString(1, "1");
- cstmt.registerOutParameter(2, java.sql.Types.VARCHAR);
- cstmt.executeUpdate();
- cstmtControl.setReturnValue(1);
- cstmt.getString(2);
- cstmtControl.setReturnValue("5,4,3");
- cstmt.close();
- cstmtControl.replay();
- String rusult = dao.getNumber();
- Assert.assertEquals("5,4,3", rusult);
- conControl.verify();
- cstmtControl.verify();
oh,my got!测试代码比实现代码还要多。这段代码能执行吗?
我想可以的。easymock的原理是记录-回放的模式。
我想要做的工作是:
1,记录你mock对象的工作记录,比如上面的代码我们mock对象的工作记录是:
- conn.prepareCall("{call LUCK_LOAD_COMMON(?,?)}");
- conControl.setReturnValue(cstmt);
- cstmt.setString(1, "1");
- cstmt.registerOutParameter(2, java.sql.Types.VARCHAR);
- cstmt.executeUpdate();
- cstmtControl.setReturnValue(1);
- cstmt.getString(2);
- cstmtControl.setReturnValue("5,4,3");
- cstmt.close();
如果你工作记录的代码要求有返回值的话,那么你必须提供一个自定义的值给它,否则会报错。比如上面的
- cstmt.getString(2);
- cstmtControl.setReturnValue("5,4,3"); //自己定义的返回值,用作以后的比较。
上面的是记录操作,回放的时候,easymock会把记录的操作跟你实际的代码进行比较,如果里面出了什么差错,那么不好意思你的代码有问题,请修正后再测试。
如果有兴趣可以自己试下。
经过前几篇的测试学习跟实践,我觉得有必要对这次学习做个总结。
以前我正常的设计流程是Database->Model -> Dao-> Service -> Action ->View。这样的设计伴随我1年多了,这样的设计方式好吗?这样的设计高效吗? 代码质量能保证吗? 我可以很肯定的回答,不能,如果数据库一该,我要在表格里面添加一个字段,或者什么的。那么它将会牵连到很多其他,修改的动作如下:Database->Model -> Dao-> Service -> Action ->View。 噢,my got,几乎跟设计的一样多,甚至更多,因为在修改的过程中你就算有再好IDE去重构它也不能保证它的正确性。然后你就要去测试,测试它的正确性。也许测试的过程将是修改过程的几倍时间。所以我个人觉得这样的设计方式是不高效的。总而言之就是这样的设计迟早会出问题的?
为什么会这样呢?难道就没有一种解决办法吗? 经过这段日子学习我发现,以前的设计不能很好的保证质量是因为你没有足够的单元测试去支撑着它,所以你改了代码后缺乏一个很好的手段去保持这段代码的质量,换句话的意思就是,没有一个静态的人去监督你的工作(我把单元测试比喻为静态的人,它只做一件事,就是督促你的代码不出问题)。
好了。我们已经找到了适合保证我们代码质量的方法了。但是我们还得提高我们的开发效率啊。这又怎么办呢?是不是还按照以前的方式吗?我想自己浑浑噩噩的活了20多年了。我想换种活法了,想找种更刺激,更有意义的生活方式。
设计有时候更生活是一样的,应该经常探索,经常实践才能感受的更多。
那好吧我们就来个彻底的变革吧。怎么变呢? 很明显:那就是TDD。
该怎么做呢?
以前的方式:Database->Model -> Dao-> Service -> Action ->View。
TDD的方式:Test->其他。
先看看下面Dao的例子吧:以前的方式:IBaseDao -> BaseDao -> BaseDaoTest。
TDD:BaseDaoTest->IBaseDao->BaseDao.
- public void testFindAccountByName(){
- Account a = new Account("wuhua");
- ht.find("from Account as a where a.name=?", a.getName());
- List l = new ArrayList();
- l.add(a);
- control.setReturnValue(l);
- control.replay();
- Account result = accountDao.findAccounByName(a.getName());
- Assert.assertEquals(a.getId(),result.getId());
- Assert.assertEquals(a, result);
- control.verify();
- }
用途就是:以为上面的从上面的代码我很清楚自己以后要做什么。1,要建立一个Model,里面起码有一个name属性,然后你会发现我们要测试的功能段是 accountDao.findAccounByName(a.getName()); 里面我们要求测试的SQL是 from Account as a where a.name=?, 意图明确吧。好,
我们写下实际代码吧。
- public Account findAccounByName(String name) {
- List l = this.getHibernateTemplate().find("from Account as ", name);
- if(l != null && l.size() >=1)
- return (Account) l.get(0);
- else
- return null;
- }
- public Account findAccounByName(String name) {
- List l = this.getHibernateTemplate().
- find("from Account as a where a.name=?", name);
- if(l != null && l.size() >=2)
- return (Account) l.get(0);
- else
- return null;
- }
后来查了半天发现原来
- List l = new ArrayList();
- l.add(a);
- if(l != null && l.size() >=2)
- return (Account) l.get(0);
- else
- return null;
最后改了这段代码
- public Account findAccounByName(String name) {
- List l = this.getHibernateTemplate().find("from Account
- as a where a.name=?", name);
- if(l != null && l.size() >=1)
- return (Account) l.get(0);
- else
- return null;
- }
终于通过了。绿色,绿色,我看到了。我对主管说。主管笑了。我也笑了
最后我郁闷下,写这篇文章足足话了我22个小时,
第一次写好了。杀毒突然重启。所以全没了。
第二次,提交不了。然后忘记备份,又全没了
第三次成功了。过程跟TDD差不多。