单元测试之实践三 Service的测试
2007-04-03 16:18
267 查看
测试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的方法,
然后自定义返回一个自己预期的对象,
最后通过比较这个对象判断结果是否是自己想要的
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的方法,
然后自定义返回一个自己预期的对象,
最后通过比较这个对象判断结果是否是自己想要的
相关文章推荐
- 你的单元测试有多稳定?提升自动测试质量的最佳实践
- JUnit单元测试实践:测试工具类和方法(EmptyUtils)
- 单元测试之Service的测试
- JUnit单元测试实践:测试工具类和方法(EmptyUtils)
- Android 中的单元测试(使用ServiceTestCase 进行 Service测试 例子)
- ionic之如何应用karma进行单元测试(2)-测试controller和service
- 业务逻辑层(service层)单元测试的实践
- JUnit单元测试实践:测试工具类和方法(EmptyUtils)
- 北航课程 软件测试工具与实践7: JUnit与单元测试
- spring boot写单元测试(测试service层)
- Spring Boot(三):单元测试(工程师必备素养)之service测试
- 单元测试之实践四 Action的测试
- JUnit单元测试实践:测试工具类和方法(EmptyUtils)
- android单元测试最佳实践一:android studio测试环境搭建
- angular单元测试与自动化UI测试实践
- 你的单元测试有多稳定?提升自动测试质量的最佳实践
- 你的单元测试有多稳定?提升自动测试质量的最佳实践
- JUnit单元测试实践:测试工具类和方法(EmptyUtils)
- 北航课程 软件测试工具与实践9: HP Mercury WinRunner
- 单元测试中的常用测试模式