ITeye博客

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

flash7783 · 2010-08-30 10:13 · javascript · 研发管理 · Markdown

测试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. accountDao.save(account);
  5. }

测试代码

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. public void testFindAccountByName() {
  8. String name = "wuhua";
  9. accountDao.findAccounByName(name);
  10. Account a = new Account("wuhua");
  11. a.setId(name);
  12. control.setReturnValue(a);
  13. control.replay();
  14. Account at = as.findAccounByName(name);
  15. Assert.assertEquals(name, at.getId());
  16. Assert.assertEquals(a, at);
  17. control.verify();
  18. }

首先我们建立一个关键字查询,name="wuhua";
然后调用Dao的方法,
然后自定义返回一个自己预期的对象,
最后通过比较这个对象判断结果是否是自己想要的

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。