2012-07-30 122 views
2

在我的控制器中,我有一个操作,它使用条件来打分贝和获取结果。嘲笑单元测试中的控制器条件... grails

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)时抛出一个异常。例外是“groovy.lang.MissingMethodException:没有方法的签名:testSearch_closure3.docall()适用于争论类型:

PS-但是,如果我从控制器中的c.list()中删除参数,如下所示:

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

那么,其工作正常。不知道这里的问题是什么。任何帮助表示赞赏

回答

2

这是因为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 
+0

修改名单列出:{对象PARAMS = NULL,封闭CLS - >新DomainObj(ID:1)} ....工作现在 – Npa 2012-07-30 16:49:16

+0

IAM面临的另一个问题。在控制器中有一行result.totalCount,其中结果是条件查询的结果。但测试中的嘲讽响应只有modCount,因为它仅仅是一个列表。因此它会在控制器的result.totalCount中抛出异常。有什么方法可以在测试中设置totalCount? – Npa 2012-07-30 16:52:13

+0

@ user1474968我编辑了我的答案 – Xeon 2012-07-30 18:38:29