当 PostConstruct 调用注入服务时 Spock 失败
Spock fails when PostConstruct calls a injected service
谁能告诉我如何解决在模拟之前调用 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
如果您有@TestFor(MyService) - MyService 实例将自动创建,您可以将其用作'service'。而且您不需要手动创建 MyService。
所以只能删除@TestFor(MyService) 或使用它并删除MyService 服务。
但是你还需要正确的mock 'secondService'
@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()
}
}
谁能告诉我如何解决在模拟之前调用 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
如果您有@TestFor(MyService) - MyService 实例将自动创建,您可以将其用作'service'。而且您不需要手动创建 MyService。
所以只能删除@TestFor(MyService) 或使用它并删除MyService 服务。
但是你还需要正确的mock 'secondService'
@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()
}
}