Something I have heard in the past is the bemoaning about injecting a dependency just for the sole sake of being able to test the use of that dependency, and while reading email today I saw that someone built a “handy utility” for replacing dependencies without having to make a setter or constructor. While they saw this as a great way to bypass code created “just for testing” I disagree on the reason that Test just quite simply are not Tests.
When you are doing Test Driven Design (note that I didn’t say Development) you are not just creating an exhaustive suite of unit tests to test your code and you’re not “testing everything that could break”, if you are you are doing it wrong. Rather, by test driven design you are describing your design… you are describing the API, how it behaves, how it works. Most importantly, you are using your tests as examples of how the system under test works in a given situation and using the examples to drive how your system is designed!
As such, using Inversion of Control or Dependency Injection to provide the dependencies to your System Under Test is in no way, shape or form creating needless test code… I will tell you right now that if you are creating protected setters to inject dependencies you are misunderstanding Dependency Injection and need to re-read up on it a bit. The way I see it you should have a system that is composed of two kinds of objects… objects that have new littered all over to create objects and objects that do things (sometimes with dependencies provided to them). With this being the case, you don’t want objects that do things and have the new keyword all over the place.
I’ve seen a lot of code written that uses multiple constructors, one that takes a dependency and one no-arg constructor that creates the dependencies it needs itself. This is a general example of code that one might complain is playing lip service to the tests around it, but my solution is do away with the no-arg constructor. You’re injecting at the wrong level. Either do one of the following:
- Use a Dependency Injection framework like Guice, Spring, or PicoContainer
- Push the dependency creation to the client
- Organize code into modules, with the module definitions creating and wiring the dependencies
Just my random thoughts on it… with all the confusion of Test Driven Development being focused on Testing, you can see why I’ve been really preferring Behavior Driven Development for the aspects that BDD is often called “TDD Done Right”.
Dependency Injection is about design, which happens to make you design easier to decouple from dependencies and therefore easier to provide Mocks,Stubs,Fakes,or Spies to describe how the system uses those dependencies.

