您尝试的 metaClass 方法存在一些问题。 where 方法是静态的,所以不要这样:
MyModel.metaClass.where = {
return [myModel1, myModel2]
}
使用这样的东西:
MyModel.metaClass.static.where = {
return [myModel1, myModel2]
}
另一个问题是 where 方法返回 List 的 MyModel 实例。相反,您希望返回一些将响应 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
}
}