如何在我的域中模拟瞬态服务?

How do I mock a transient service in my domain?

我正在使用 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),但无济于事。

如何正确模拟此服务以便我可以测试我的自定义验证器?我开始对这个失去耐心了。

这里有一个单元测试的例子class:

@TestMixin(GrailsUnitTestMixin)
@Mock(CustomField)
class MyRepoServiceSpec extends Specification {
    def "test"() {
        given: "mock"
        def serviceMock = Mock(MyRepoService) // Spock mocking
        serviceMock.getCurrentRepo() >> { Myinfo.build() }
        CustomField customField = new CustomField(name : 'hulk')
        customField.myRepoService = serviceMock

        when: "validating field"
        def isValid = customField.validate()

        then: "validation pass"
        isValid == true
    }
}