带有服务的 Grails 规范测试

Grails specification test with service

我正在尝试在 Spock 规范测试中使用服务。

 def "Registrate company and user with some valid data"() {
     given:
     RegistrationService registrationService = Mock()
     controller.registrationService = registrationService

     when:
     def data =  registrationService.register('test@test.sk','a','a','a','12345576','159159159','a','a','a','a','a')

     then:
     assert data.instance1.hasErrors() == false
     assert data.instance2.hasErrors() == false
     assert data.instance3.hasErrors() == false
}

我收到空指针异常java.lang.NullPointerException: Cannot get property 'instace1' on null object.

如果我 运行 通过我的控制器提供服务,那么一切正常。

服务returns这个[instance1:instance1,instance2:instance2,instance3:instance3]

您需要在调用方法时指定模拟 RegistrationService returns 的内容,例如

def "Registrate company and user with some valid data"() {
    given:
    RegistrationService registrationService = Stub()

    // you should probably be a bit more precise about the arg-list
    registrationService.register(*_) >> 
            [instance1: instance1, instance2: instance2, instance3: instance3]

    controller.registrationService = registrationService

    when:
    def data = registrationService.register('test@test.sk','a','a','a','12345576','159159159','a','a','a','a','a')

    then:
    !data.instance1.hasErrors()
    !data.instance2.hasErrors()
    !data.instance3.hasErrors()
}

请注意,在 then: 块中没有必要使用 assert,如果每个语句 returns 为真值,则每个语句将被视为成功,否则将被视为失败。

更新

我注意到报告的错误信息是

Cannot get property 'instace1' on null object.

看来您的代码中某处可能缺少 "n"