如何在我的域中模拟临时服务?

时间:2015-02-28 09:07:25

标签: grails spock

我正在使用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为null或类似的东西。

我已经浏览了这个帖子:( Unit testing a domain with transient property),但无济于事。

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

1 个答案:

答案 0 :(得分:0)

以下是针对您的案例的单元测试类的示例:

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