关闭

单元测试之Service的测试

发表于:2007-10-29 13:31

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:网络转载

        测试Service,因为Service依赖的Dao, 所以只需Mock一个Dao即可。在这里我详细的介绍关于注册这个功能的测试
java 代码
 
  1. public interface IAccountService extends IBaseService {  
  2.       Account findAccountById(String id);  
  3.       Account findAccounByName(String name);  
  4.       void regist(Account account) throws ObjectExistsException;  
  5. }  
        注册功能的实现。
java 代码
 
  1. public void regist(Account account) throws ObjectExistsException {  
  2.     if(accountDao.findAccounByName(account.getName()) != null)  
  3.         throw new ObjectExistsException("User's name is exists!");  
  4.       
  5.     accountDao.save(account);  
  6. }  

测试代码
java 代码
 
  1.     protected void setUp() throws Exception {  
  2.         control = MockControl.createControl(IAccountDao.class);  
  3.         accountDao = (IAccountDao) control.getMock();  
  4.         as = new AccountService();  
  5.         as.setAccountDao(accountDao);  
  6.     }  
  7.   
  8.   
  9. public void testFindAccountByName() {  
  10.         String name = "wuhua";  
  11.         accountDao.findAccounByName(name);  
  12.         Account a = new Account("wuhua");  
  13.         a.setId(name);  
  14.         control.setReturnValue(a);  
  15.         control.replay();  
  16.         Account at = as.findAccounByName(name);  
  17.         Assert.assertEquals(name, at.getId());  
  18.         Assert.assertEquals(a, at);  
  19.         control.verify();  
  20.     }  

        首先我们建立一个关键字查询,name="wuhua";
        然后调用Dao的方法,
        然后自定义返回一个自己预期的对象,
        最后通过比较这个对象判断结果是否是自己想要的
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号