【问题标题】:mocking Controller criteria in unit test...grails在单元测试中模拟控制器标准...... grails
【发布时间】:2012-07-28 07:28:10
【问题描述】:

在我的控制器中,我有一个操作,它使用标准来命中 db 并获取结果。

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() {
    }

然后,它正在工作。不确定这里的问题是什么。任何帮助表示赞赏

【问题讨论】:

    标签: java hibernate grails junit criteria


    【解决方案1】:

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

    【讨论】:

    • 将列表修改为列表:{Object params=null, Closure cls -> new DomainObj(id:1)} 工作......
    • 现在我面临另一个问题。在控制器中有一行 result.totalCount 其中 result 是条件查询的结果。但是测试中的模拟响应只有 modCount,因为它只是一个列表。因此,它在控制器中的 result.totalCount 处引发异常。有什么方法可以在测试中设置 totalCount 吗?
    • @Xeon ...我仍然无法在测试用例中模拟分页结果列表。我总是将 arraylist 作为模拟标准结果,并且在控制器中失败了......我已经解释了这个问题以及stackoverflow.com/questions/11726279/… 的代码
    • 感谢至强..但如果您能够在新线程中回复将对我有所帮助...再次感谢
    猜你喜欢
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 2013-03-09
    • 2020-01-05
    相关资源
    最近更新 更多