測試Service,因為Service依賴的Dao, 所以只需Mock一個Dao即可。在這里我詳細的介紹關于注冊這個功能的測試
java 代碼
- public interface IAccountService extends IBaseService {
- Account findAccountById(String id);
- Account findAccounByName(String name);
- void regist(Account account) throws ObjectExistsException;
- }
注冊功能的實現。
java 代碼
- public void regist(Account account) throws ObjectExistsException {
- if(accountDao.findAccounByName(account.getName()) != null)
- throw new ObjectExistsException("User's name is exists!");
-
- accountDao.save(account);
- }
測試代碼
java 代碼
- protected void setUp() throws Exception {
- control = MockControl.createControl(IAccountDao.class);
- accountDao = (IAccountDao) control.getMock();
- as = new AccountService();
- as.setAccountDao(accountDao);
- }
-
-
- public void testFindAccountByName() {
- String name = "wuhua";
- accountDao.findAccounByName(name);
- Account a = new Account("wuhua");
- a.setId(name);
- control.setReturnValue(a);
- control.replay();
- Account at = as.findAccounByName(name);
- Assert.assertEquals(name, at.getId());
- Assert.assertEquals(a, at);
- control.verify();
- }
首先我們建立一個關鍵字查詢,name="wuhua";
然后調用Dao的方法,
然后自定義返回一個自己預期的對象,
最后通過比較這個對象判斷結果是否是自己想要的 |