6

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?

Lucas
  • 3,059
  • 5
  • 33
  • 48

2 Answers2

8

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
    }
}
Dave Bower
  • 3,487
  • 26
  • 28
  • Thanks. I'm testing a service that depends of anothers services and i was instantiating it and because of this, i wasn't get the benefits of DI. – Lucas Feb 16 '10 at 15:37
  • 2
    Just a side note. Integration tests should not extend GrailsUnitTestCase depending on version this can cause serious issues with your ConfigurationHolder.config being null. Yes grails create-integration-test in many version does create a test that extends GrailsUnitTestCase but this is a bug that has been fixed recently. – Ben Doerr Jan 31 '11 at 20:30
  • Why does the answer say "Of course, if you instantiate a class that requires injection" you won't get DI? Why is that generally the case? It wasn't obvious to me -- though I painfully figured it out. – Peter N. Steinmetz Nov 25 '12 at 01:09
  • DI is performed via the framework. The framework only knows about objects which it instantiates. – Dave Bower Feb 04 '14 at 15:18
3

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.

Perception
  • 79,279
  • 19
  • 185
  • 195
dkstyle0
  • 51
  • 2
  • 1.3.7 and greater. This is a problem in 2.4.x as well. Additionally, for controller integration tests you must instantiate the controller: `def fooController = new FooController()` - then dependencies will be correctly wired up. –  Sep 25 '15 at 18:09