Grails单元测试中的注入服务 [英] Inject Services in Grails Unit Test
本文介绍了Grails单元测试中的注入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道您可以使用以下方法简单地在单元测试方法中注入服务:
I know that you can simply inject a service in unit test method using:
defineBeans {
someService(SomeService)
}
但是当我需要在服务中注入服务(服务 someService
自己调用另一个服务 some2Service
)。当我运行测试时,我收到以上代码:
But when I need to inject service inside a service (the service someService
calls itself another service some2Service
). When I run the test with above code I receive:
Message: Cannot invoke method someMethod() on null object
是否可以在单元测试中将服务注入到服务中?
Is it possible to inject a service into a service in the unit test?
谢谢。 ; - )
推荐答案
要在单元测试中使用spring bean,您需要执行以下操作:
To use spring beans in a unit test you need to do the following:
- 在
defineBeans
关闭中包含测试所依赖的所有服务和其他bean。 - 为需要注入其他bean的bean设置
autowire
属性为true
。
- Include all the services and other beans the test depends on in the
defineBeans
closure. - Set the
autowire
property totrue
for beans that need to have other beans injected.
例如:
defineBeans {
someService(SomeService) { bean ->
bean.autowire = true
}
some2Service(Some2Service)
}
这篇关于Grails单元测试中的注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文