How to handle dependency injection with nested dependencies

Recently I managed to get myself rather confused trying to use Test Driven Development to test a specific business logic class (Class A). Part of the business logic had been refactored into a seperate business logic class (Class B), this class had a set of dependencies that were properly coded to allow for dependency injection. The problem was that Class A also included all the dependencies of Class B, and when the class B was called the dependencies were setup based on the dependencies of Class A. This all seemed ‘ok’ until I decided that a unit test of Class A should not really test Class B. (This is obvious when you think about it, but because Class B had originally been part of Class A it hadn’t clicked straight away). Having never worked with dependency injection where there are nested dependencies I had a little trouble refactoring to allow class B to be mocked.

Following are the guidelines I reached for working with nested dependencies:

  • The dependencies of Class B should not be included in the dependencies of Class A
  • The operations in Class B need to be extracted into an interface (IClassB)
  • Class B should implement interface IClassB
  • Class A should operate on an instance of this interface
  • A Mock of Class B is created that also implements IClassB
  • When setting up Class A (e.g. from a unit test) the dependency on IClassB needs to be initialised using the MockClassB

If using default constructors to setup the ‘default’ dependencies (I believe this is known as “poor man’s dependency injection”) then the default constructor for Class A should simply create a default instance of ClassB (allowing Class B to setup its own default dependencies)

Advertisements

About Alex McMahon

I am a software developer, interested in .net, agile, alt.net. I've previously specialised with .net 3.0 technologies like WCF, whereas now I am trying to specialise in agile development and best practice and patterns. I am obsessed with looking at the latest technologies, tools, and methods, and trying them out. I am currently employed by Rockwell Collins in the UK.
This entry was posted in dependency injection, development, IoC, methodology, mocks, TDD, testing. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s