TesterHQ - The Evil Tester Blog Aggregator

Mar 4, 2008 - 2 minute read - Agile Evil Tester

A simple explanation of dependency injection

Original Blog Posting on [blog.eviltester.com]

For the longest time I didn’t know what dependency injection meant - anytime I looked it up I glazed over thinking it really complicated.

I only recently found out while learning TDD that I can describe dependency injection in terms of - pass an object in as a parameter instead of instantiating it in the class or method.

But as soon as I learn this, I encounter a presentation that would have taught me this anyway - so I pass it on now in case you don’t know what dependency injection refers to.

The following presentation on ‘testability’ (from a developer’s perspective, i.e. how do you make your code testable) has a good summary slide that makes dependency injection seem simple.

About 23 minutes in designing for testability shows:

   void f(){
      Database db = Database.getInstance();
      db.query("DELETE FROM ACCOUNTS"); 
   }

But this makes the code hard to test as the database gets instantiated using a static within the method f. If we want to test method f we will find it hard to do because it connects to a database which we can’t control from our test.

If we ‘inject’ the ‘dependency’ on the database then we have the option of mocking the database or using an in memory database.

   void f(Database db){
     db.query("DELETE FROM ACCOUNTS");
   }

Then in the real world we can do:

f(Database.getInstance());

But in the test we can do

f(new Mock(Database.class));

There - dependency injection.

The presentation mentions a few Java frameworks for dependency injections, recommending Guice (the Wikipedia:Dependency Injection page has a longer list)

I found the presentation useful and on the basis of this presentation I will go away and learn a little bit more about TestNG.