Npa
Npa

Reputation: 617

mocking Controller criteria in unit test...grails

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

def c = DomainObj.createCriteria()
def result =[]
result = c.list(params) {
    'eq'("employerid", id)
    }

I am trying to mock this criteria in my unit test.

def mycriteria =[
list: {Closure cls -> new DomainObj(id:1)}
]                                   ]
DomainObj.metaClass.static.createCriteria = {mycriteria}

The above does not work. It throws out an exception when c.list(params) is being executed. The exception is "groovy.lang.MissingMethodException: No signature of method: testSearch_closure3.docall() is applicable for arguement types:

PS- However, if i remove params from c.list() in controller i.e. see below:

def c = DomainObj.createCriteria()
    def result =[]
result = c.list() {
    }

then, it is working. Not sure what the problem here is. Any help is appreciated

Upvotes: 2

Views: 1537

Answers (1)

Xeon
Xeon

Reputation: 5989

This is because of the default parametes of the list method.

e.g.

def method(Object[] params = {/*no params*/}, Closure c, etc. etc.)  {...}

above can be used like:

method(c: {...})
method(params) {...}
method(params, {...}) // this is the same as the above
method(params:new Object[]{...}, c: {...}) // and this also
//etc.

you change metaClass and add method list that takes only one parameter.

So your mycriteria should look like this:

def mycriteria = [
    list: {Object params=null, Closure cls -> new DomainObj(id:1)}
    //or recreate `list` declaration with all parameters
]
DomainObj.metaClass.static.createCriteria = {mycriteria}

consider this example:

def cl = {String a = 'x', b -> println a +','+ b}
cl("z")

output is:

x, z

EDIT

To change returned object you do as previously:

class A {
}

A.metaClass.static.createCriteria = {
    [list: 
        {def a = new A(); a.metaClass.totalResult=5; a}
    ]
}

def c = A.createCriteria()
def result = c.list()
println result.totalResult

Upvotes: 2

Related Questions