路是爬出来的

单元测试之实践三 Service的测试

测试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的方法,

然后自定义返回一个自己预期的对象,

最后通过比较这个对象判断结果是否是自己想要的

posted on 2006-12-30 09:06 路是爬出来的 阅读(346) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: