Grails…Mocking criteria that returns PagedResultLi

2019-07-24 01:28发布

问题:

In my controller, i have an action which uses criteria to hit db and fetch results.

params.max = Math.min(params.max ? params.int('max') : 20, 100)    
def c = DomainObj.createCriteria()
    def result =[]
    result = c.list(params) {
        'eq'("employerid", id)
        }

I have mocked this call in my testcase this way:

def result=[DomainObj1]         
            def mycriteria =[
                list: {Object params=null,Closure cls -> result}                    
                ]

DomainObj.metaClass.static.createCriteria = {mycriteria}

Works fine so far.

But in the controller, there is a line where the code says result.totalCount where result is the output of criteria query and is of PagedResultList type. But in the test case, iam mocking the result as an arrayList, but not as PagedResultList. So, code breaks at result.totalCount if run from the test case.

Any idea of how can I mock the criteria response to PagedResultList instead of arraylist so that it has totalCount

回答1:

Take a look at its interface. You can just compose it like

result = new PagedResultList(list: inctanceList, totalCount: inctanceList.size())