假设我有查询的地方:
MyModel.where {
group == 'someGroup' && owner {association == association}
}.list()
我如何在测试中模拟它?我尝试过这样的事情:
MyModel.metaClass.where = {
return [myModel1, myModel2]
}
但是,它没有用。所以,我试过这样做:
def myModelMock = Mock(MyModel)
myModelMock.where(_) >> [myModel1, myModel2]
它仍然没有奏效。还有哪些方法可以模拟该查询?我只想要它返回一个列表。 :(
答案 0 :(得分:2)
您尝试过的metaClass方法存在一些问题。 where
方法是静态的,而不是:
MyModel.metaClass.where = {
return [myModel1, myModel2]
}
使用类似的东西:
MyModel.metaClass.static.where = {
return [myModel1, myModel2]
}
另一个错误的是您使用where
方法返回List
个MyModel
个实例。相反,您希望返回一些将响应list()
方法的对象,并且该对象应返回{My} MyModel的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
}
}