当PostConstruct调用注入的服务时,Spock失败

时间:2017-07-06 13:10:56

标签: grails spock

任何人都可以告诉我如何解决在模拟之前调用PostConstruct的问题:

服务:

class MyService {
    SecondService secondService // injected

    @PostConstruct
    void init() {
        myFunction()
    }

    void myFunction() {
        secondService.doSomething()
    }

}

测试:

@TestFor(MyService)
class MyServiceSpec extends Specification {
   void "testing my service"() {
      given:
         MyService service = GroovySpy(MyService) {
             myFunction() >> null
         }
      then:
         true
   }
}

给出以下错误:

Invocation of init method failed; nested exception is java.lang.NullPointerException: Cannot invoke method doSomething() on null object

1 个答案:

答案 0 :(得分:2)

如果您有@TestFor(MyService),我们会自动创建MyService实例,您可以将其用作' service'。而且您不需要手动创建MyService。

因此,您只能删除@TestFor(MyService)或使用它并删除MyService服务。

但你还需要正确地模拟第二服务'

@FreshRuntime
@TestFor(MyService)
class MyServiceSpec extends Specification {

    def secondService = GroovyMock(SecondService)

    def doWithSpring = {
        secondService(InstanceFactoryBean, secondService, SecondService)
    }

    void "testing my service"() {
        when:
        service.myFunction()
        then:
        1 * secondService.doSomething()
    }
}