开发者

Dependency injection in Grails integration tests

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?


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
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜