【问题标题】:How do I mock a transient service in my domain?如何在我的域中模拟临时服务?
【发布时间】: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),但无济于事。

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

【问题讨论】:

  • 请详细说明“或类似的东西”。

标签: grails spock


【解决方案1】:

这是您案例的单元测试类示例:

@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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 2018-12-12
    • 2019-09-30
    相关资源
    最近更新 更多