測(cè)試Service,因?yàn)镾ervice依賴(lài)的Dao, 所以只需Mock一個(gè)Dao即可。在這里我詳細(xì)的介紹關(guān)于注冊(cè)這個(gè)功能的測(cè)試
java 代碼
- public interface IAccountService extends IBaseService {
- Account findAccountById(String id);
- Account findAccounByName(String name);
- void regist(Account account) throws ObjectExistsException;
- }
注冊(cè)功能的實(shí)現(xiàn)。
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);
- }
測(cè)試代碼
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();
- }
首先我們建立一個(gè)關(guān)鍵字查詢(xún),name="wuhua";
然后調(diào)用Dao的方法,
然后自定義返回一個(gè)自己預(yù)期的對(duì)象,
最后通過(guò)比較這個(gè)對(duì)象判斷結(jié)果是否是自己想要的 |