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

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

     when:
     def data =  registrationService.register('[email protected]','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.
如果我通过 Controller 运行该服务,则一切正常。

服务返回此[instance1:instance1,instance2:instance2,instance3:instance3]

最佳答案

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

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('[email protected]','a','a','a','12345576','159159159','a','a','a','a','a')

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

注意,没有必要在assert块中使用then:,如果每个语句返回真实值,则将其视为成功;如果返回false,则将其视为失败。

更新资料

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



所以看起来您的代码中某处可能缺少“n”

关于java - 带有服务的Grails规范测试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38607614/

10-11 10:18