【问题标题】:Grails 2.3.9 & Spock: How do mock the returns of "where" queries?Grails 2.3.9 & Spock:如何模拟“where”查询的返回?
【发布时间】:2014-07-07 17:12:48
【问题描述】:

假设我有这个 where 查询:

MyModel.where {
            group == 'someGroup' && owner {association == association}
}.list()

如何在我的测试中模拟它?我试着做这样的事情:

MyModel.metaClass.where = {
       return [myModel1, myModel2]
}

但是,它没有用。所以,我尝试这样做:

def myModelMock = Mock(MyModel)
myModelMock.where(_) >> [myModel1, myModel2]

它仍然没有工作。我还有什么其他方法可以模拟该查询?我只是希望它返回一个列表。 :(

【问题讨论】:

  • 如何将该查询移动到一个方法,然后模拟该方法以返回一个列表?

标签: unit-testing grails mocking spock


【解决方案1】:

您尝试的 metaClass 方法存在一些问题。 where 方法是静态的,所以不要这样:

MyModel.metaClass.where = {
   return [myModel1, myModel2]
}

使用这样的东西:

MyModel.metaClass.static.where = {
   return [myModel1, myModel2]
}

另一个问题是 where 方法返回 ListMyModel 实例。相反,您希望返回一些将响应 list() 方法的对象,并且应该返回 `MyModel.xml 的 List。像这样的...

MyModel.metaClass.static.where = { Closure crit ->
    // List of instances...
    def instances = [myModel1, myModel2]

    // a Map that supports .list() to return the instances above
    [list: {instances}]
}

希望对你有帮助。

编辑:

我认为上面的代码解决了所提出的问题,但我应该提一下,更常见的做法是使用 mockDomain 方法提供模拟实例:

// grails-app/controllers/demo/DemoController.groovy
package demo

class DemoController {

    def index() {
        def results = MyModel.where {
            group == 'jeffrey'
        }.list()

        [results: results]
    }
}

然后在测试中...

// test/unit/demo/DemoControllerSpec.groovy
package demo

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(DemoController)
@Mock(MyModel)
class DemoControllerSpec extends Specification {

    void "this is just an example"() {
        setup:
        mockDomain(MyModel, [new MyModel(group: 'jeffrey'), new MyModel(group: 'not jeffrey')])

        when:
        def model = controller.index()

        then:
        // make whatever assertions you need
        // make sure you really are testing something
        // in your app and not just testing that 
        // the where method returns what it is supposed
        // to.  
        model.results.size() == 1
    }
}

【讨论】:

    猜你喜欢
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    相关资源
    最近更新 更多