在我的 Controller 中,我有一个使用条件来命中数据库并获取结果的操作。
def c = DomainObj.createCriteria()
def result =[]
result = c.list(params) {
'eq'("employerid", id)
}
我试图在单元测试中模拟这个标准。
def mycriteria =[
list: {Closure cls -> new DomainObj(id:1)}
] ]
DomainObj.metaClass.static.createCriteria = {mycriteria}
上面的方法不起作用。当 c.list(params) 执行时它会抛出异常。异常(exception)是“groovy.lang.MissingMethodException:没有方法签名:testSearch_closure3.docall()适用于争论类型:
PS-但是,如果我从 Controller 中的 c.list() 中删除参数,即见下文:
def c = DomainObj.createCriteria()
def result =[]
result = c.list() {
}
然后,它就可以工作了。不确定这里的问题是什么。任何帮助表示感谢
最佳答案
这是因为 list
方法的默认参数。
例如
def method(Object[] params = {/*no params*/}, Closure c, etc. etc.) {...}
上面可以这样使用:
method(c: {...})
method(params) {...}
method(params, {...}) // this is the same as the above
method(params:new Object[]{...}, c: {...}) // and this also
//etc.
您更改 metaClass
并添加仅采用一个参数的 list
方法。
所以你的mycriteria
应该是这样的:
def mycriteria = [
list: {Object params=null, Closure cls -> new DomainObj(id:1)}
//or recreate `list` declaration with all parameters
]
DomainObj.metaClass.static.createCriteria = {mycriteria}
考虑这个例子:
def cl = {String a = 'x', b -> println a +','+ b}
cl("z")
输出为:
x, z
编辑
要更改返回的对象,请像以前一样执行操作:
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
关于java - 在单元测试中模拟 Controller 标准...grails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11724722/