3 ms·
When all your modules' dependencies are injected as constructor parameters, it's straightforward to mock those dependencies when TDD'ing the module. Constructo
by EdSharkey 9y ago
When all your modules' dependencies are injected as constructor parameters, it's straightforward to mock those dependencies when TDD'ing the module. Constructor parameter injection is really vital to isolate the SUT (system under test) when writing your tests. Any other type of injection is magical, and should be avoided.
At test-runtime, one will pass mock objects to the SUT's constructor using the new keyword. These mock objects are used to rig up specific preconditions that drive the scenario to be tested. Mocks can also be used to assert that the SUT called the dependency as expected with parameters.
At runtime, the IoC container handles instantiation of the module and injects the dependencies as appropriate constructor params.
I assume you asked this because Spring Framework is the poster child of dependency injection and IoC in the Java world. With all the Aspect-Oriented Programming and proxification and scope twizzling that occasionally blooms in the Spring ecosystem that is all wired-up using Spring DI, I think Spring sometimes gets a bad rep. Only abusers of those features get bad reps with me. Spring as a whole is a trove of nicely built systems with lots of classy 3rd party integrations. I personally prefer using Google Guice for DI because it is a standalone system, it eschews doing classpath scanning to identify injectable classes which I think makes it faster especially at startup, and it has decent integrations with 3rd party libraries.
- jacques_chester 9y agoFWIW, the Spring team fairly emphatically advise against anything but constructor injection[0], to the point that a major feature of Spring Framework 5 was to rework the code to be exclusively constructor injected[1]. [0] http://olivergierke.de/2013/11/why-field-injection-is-evil/ http://olivergierke.de/2013/11/why-field-injection-is-evil/ [1] https://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-Spring-Framework-5.x#general-core-revision https://github.com/spring-projects/spring-framework/wiki/Wha...