假设我有这样的查询:
MyModel.where {
group == 'someGroup' && owner {association == association}
}.list()
我如何在测试中模拟它?我试着这样做:
MyModel.metaClass.where = {
return [myModel1, myModel2]
}
但是,它没有工作。所以,我试着这样做:
def myModelMock = Mock(MyModel)
myModelMock.where(_) >> [myModel1, myModel2]
仍然不能工作。还有什么方法可以模拟这个查询?我只想让它返回一个列表。(
您尝试的metaClass方法有几处错误。where
方法是静态的,所以不要这样写:
MyModel.metaClass.where = {
return [myModel1, myModel2]
}
像这样使用:
MyModel.metaClass.static.where = {
return [myModel1, myModel2]
}
另一个错误的是,您有where
方法返回MyModel
实例的List
。相反,您希望返回一些对象,该对象将响应list()
方法,并且应该返回List
' MyModel。像这样…
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
}
}