Grails 集成测试中的依赖注入
我正在测试我的应用程序的一项服务,该服务依赖于运行时的其他服务。测试时,依赖注入似乎不起作用。运行集成测试时,依赖注入在 Grails 工件中是否有效?
I'm testing a service of my application thats depends of another services in runtime. When testing, the dependency inject seems doesn't works. Does dependency injection works in Grails artefacts when running integration tests?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,当运行测试(即集成目录中的测试)时,应用程序将启动,所有 bean 都会被创建并注入,就像应用程序实际运行一样。测试应用程序和运行应用程序之间的唯一区别应该是配置环境。
当然,如果您在测试中使用“new”运算符实例化一个需要注入的类,您将无法获得 DI 的好处。相反,在您的测试用例中为您的测试 bean 创建一个属性,它将被注入:
Yes, when running tests (ie those in the integration directory), the application is started and all beans are created and injected as if the app were actually running. The only difference between the test app and the running app should be the configuration environment.
Of course, if you instantiate a class that requires injection using the 'new' operator in your test you won't get the benefits of DI. Instead, create a property in your test case for the bean your testing and it will be injected:
对于那些使用 Grails 1.3.7 的人,我发现您无法使用类名来使依赖注入发挥作用。相反,将服务声明为:
然后 DI 魔法就会发生。对于 1.3.7 中的上述代码,非空断言将失败。
For those of you using Grails 1.3.7, I've found that you can't use the class name in order to get the Dependency Injection to work. Instead, declare the service as:
and then the DI magic happens. With the above code in 1.3.7 the not null assertion would fail.