类似一篇文章的例子,假设我们要测试下面这个逻辑:
class MyApp {
def factory
def logger
def doBusinessLogic(param) {
def myObj = factory.instance
myObj.doSomething(param)
myObj.doSomethingElse(param)
logger.log('Something done with: ' + param)
}
}
一般做法是要开发logger和factory的Mock,不过在Groovy中,还可以用Map或者Expando来解决问题:
可以用Expando:
def logger = new Expando()
logger.log = { msg -> assert msg == 'Something done with: ' + param }
也可以用Map:
def factory = [instance: businessObj]
这里businessObj就是我们要用于测试的对象。
下面是这个完整的测试例子:
class MyAppTest extends GroovyTestCase {
void testDoesBusinessLogic() {
// triangulate
checkDoesBusinessLogic "case1"
checkDoesBusinessLogic "case2"
}
private checkDoesBusinessLogic(param) {
def logger = setUpLoggingExpectations(param)
def businessObj = setUpBusinessObjectExpectations(param)
def factory = [instance: businessObj]
def cut = new MyApp(logger:logger, factory:factory)
cut.doBusinessLogic(param)
}
private setUpLoggingExpectations(param) {
def shouldProduceCorrectLogMessage =
{ msg -> assert msg == 'Something done with: ' + param }
def logger = new Expando()
logger.log = shouldProduceCorrectLogMessage
return logger
}
private setUpBusinessObjectExpectations(param) {
def shouldBeCalledWithInputParam = { assert it == param }
def myObj = new Expando()
myObj.doSomething = shouldBeCalledWithInputParam
myObj.doSomethingElse = shouldBeCalledWithInputParam
return myObj
}
}