[英]Grails 2.3.9 & Spock: How do mock the returns of “where” queries?
假設我有這個查詢:
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()
方法的對象,並且應該返回一個`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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.