单元测试之Service的测试

来源:互联网 发布:jquery源码 each实现 编辑:程序博客网 时间:2024/04/28 02:55
<script type="text/javascript"><!--google_ad_client = "pub-1592932103935230";/* 336x280,csdnblogs, 创建于 08-5-10 */google_ad_slot = "8315096772";google_ad_width = 336;google_ad_height = 280;//--></script> <script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
       测试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的方法,
        然后自定义返回一个自己预期的对象,
        最后通过比较这个对象判断结果是否是自己想要的
原创粉丝点击