对程序进行单元测试时,有时我们会遇到一些小麻烦,比如某些操作十分耗时,有些依赖的对象不易获取等等,这时我们就可以通过Groovy Mock或Groovy Stub来解决这些问题。Mock对方法调用的次数十分敏感,如果程序中调用的次数不在期望的调用次数范围内,则会抛出异常以致测试失败;而Stub仅仅是起到‘替身’的作用,它并不关心方法调用与否,即使方法一次都没被调用,也不会抛出异常导致测试失败。
下面让我们来看一个实际的例子吧:
import groovy.mock.interceptor.*
class User {
String name
String address
String toString() {
"Name: $name, Address: $address"
}
}
class UserDao {
User findUserByName(String name) {
if ('山风小子' == name)
return new User(name:name, address:'Shanghai')
else
return new User(name:'Anonymous User', address:'Unknown')
}
}
class ShowUserInfoService {
UserDao userDao = new UserDao()
def showInfo(String name) {
User user = userDao.findUserByName('山风小子')
println user
}
}
/*
平时下面这些代码写于单元测试中,为了简洁起见,单独抽取出来
*/
def userDaoMock = new MockFor(UserDao)
/*
UserDao对象中的findUserByName方法必须被调用1~2次,否则测试失败
同时将findUserByName方法的实现替换为return new User(name:'mock user', address:'Unknown')
*/
userDaoMock.demand.findUserByName(1..2) { String name ->
return new User(name:'mock user', address:'Unknown')
}
userDaoMock.use {
def showUserInfoService = new ShowUserInfoService()
showUserInfoService.showInfo('山风小子')
showUserInfoService.showInfo('Daniel.Sun')
//showUserInfoService.showInfo('BlueSUN')
}
def userDaoStub = new StubFor(UserDao)
/*
仅仅将findUserByName方法的实现替换为return new User(name:'stub user', address:'Unknown')
即使findUserByName方法不被调用,测试也不会失败
*/
userDaoStub.demand.findUserByName { String name ->
return new User(name:'stub user', address:'Unknown')
}
userDaoStub.use {
def showUserInfoService = new ShowUserInfoService()
showUserInfoService.showInfo('山风小子')
}
运行结果:
Name: mock user, Address: Unknown
Name: mock user, Address: Unknown
Name: stub user, Address: Unknown
附:
朝花夕拾——Groovy & Grails
posted on 2008-06-13 23:25
山风小子 阅读(4012)
评论(2) 编辑 收藏 所属分类:
Groovy & Grails