gpt4 book ai didi

unit-testing - Grails 2.3.9 和 Spock : How do mock the returns of "where" queries?

转载 作者:行者123 更新时间:2023-12-04 05:07:16 24 4
gpt4 key购买 nike

假设我有这个 where 查询:

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

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

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

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

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

还是不行。我还可以通过哪些其他方式模拟该查询?我只是想让它返回一个列表。 :(

最佳答案

您尝试的元类方法有几个问题。 where 方法是静态的,所以不是这样的:

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

使用这样的东西:

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

另一件错误的事情是您有 where 方法返回 MyModel 实例的 List。相反,您想要返回一些对象,该对象将响应 list() 方法,并且应该返回 `MyModel.List 的 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
}
}

关于unit-testing - Grails 2.3.9 和 Spock : How do mock the returns of "where" queries?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24616121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com