---
title: "单元测试之实践三 Service的测试"
author: "flash7783"
date: "2010-08-30T10:13:51Z"
tags: []
categories: ["研发管理"]
slug: "service"
draft: false
lastmod: "2010-08-30T10:13:51Z"
id: 750482
url: "https://flash7783.iteye.com/blog/750482"
---

测试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 代码

 

01. **protected** **void** setUp() **throws** Exception {
02. control = MockControl.createControl(IAccountDao.**class**);
03. accountDao = (IAccountDao) control.getMock();
04. as = **new** AccountService();
05. as.setAccountDao(accountDao);
06. }
07. **public** **void** testFindAccountByName() {
08. String name = "wuhua";
09. 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的方法，  
然后自定义返回一个自己预期的对象，  
最后通过比较这个对象判断结果是否是自己想要的