Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 727
Lucas Avatar asked Feb 16 '10 12:02

Lucas


2 Answers

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
    }
}
like image 189
Dave Bower Avatar answered Nov 19 '22 20:11

Dave Bower


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.

like image 20
dkstyle0 Avatar answered Nov 19 '22 20:11

dkstyle0