Dependency injection in Grails integration tests

烈酒焚心 提交于 2019-12-06 01:43:12

问题


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?


回答1:


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:

class MyServiceTests extends GrailsUnitTestCase {

    MyService service

    void testInjection() {
        assertNotNull service
    }
}



回答2:


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:

def myService

and then the DI magic happens. With the above code in 1.3.7 the not null assertion would fail.



来源:https://stackoverflow.com/questions/2272677/dependency-injection-in-grails-integration-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!