我有一个定义如下的服务类
class MyService {
def otherService;
def performService( ) {
Navigator.navigate( retrieveData, { otherService.doSomething(it) } );
}
def retrieveData = { Integer offset, Integer maxRows
DomainObject.list(offset,maxRows);
}
}
Navigator.navigate( Closure retriever, Closure processor ) {
def offset=0;
def batchsize=100;
while( (data=retriever(offset,batchsize)) ) {
if(data.size()==0) break;
data.each { processor(it) }
offset += data.size();
}
}
在我的测试中,我想模拟 retriveData 来检索模拟对象
@TestFor(MyService)
class MyServiceSpec extends Specification {
def "test retriever"() {
given:
service.otherService = Mock(OtherService);
service.metaClass.retrieveData = { Integer offset, Integer maxRows ->
if(offset==0) return [ Mock(DomainObject), Mock(DomainObject) ]
else return []
}
when:
service.performService();
then:
2 * otherService.doSomething(_);
}
}
事实证明,测试没有选择模拟的retrieveData,而是总是选择MyService.retrieveData 闭包,想知道模拟闭包方法的正确方法是什么。