【发布时间】:2015-02-28 22:41:22
【问题描述】:
我正在使用 Grails 2.4.4。我有一个域,其定义如下:
class CustomField {
transient myRepoService
// other properties here
static transients = [
'myRepoService'
]
static constraints = {
name validator: { val, obj ->
if (obj.nameExists(val)) {
return false
}
}
}
protected boolean nameExists(String name) {
MyInfo info = myRepoService.currentRepo.info
// do something here...
}
}
我想在 Spock 中测试它。我尝试了各种解决方案,但它们不起作用。以下是我尝试过的方法:
def myRepoService = mockFor(MyRepoService)
myRepoService.demand.currentRepo = { -> Myinfo.build() }
CustomField customField = new CustomField(name : 'hulk')
customField.myRepoService = myRepoService.createMock()
即使我添加了@Mock([MyRepoService]) 注释,这也给了我一个错误:
| org.codehaus.groovy.grails.exceptions.GrailsConfigurationException: Cannot add Domain class [class com.myapp.MyRepoService]. It is not a Domain!
我也尝试过像这样使用 MetaClass:
def service = mockFor(myRepoService)
service.metaclass.currentRepo = { -> MyInfo.build() }
CustomField.currentRepo = service
但它只是给了我一些 NullPointerException 说我的 MyRepoService 为空或类似的东西。
我也浏览了这个帖子:(Unit testing a domain with transient property),但无济于事。
如何正确模拟此服务以便我可以测试我的自定义验证器?我开始对此失去耐心。
【问题讨论】:
-
请详细说明“或类似的东西”。