Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a dependency injection system how do you unit test your code

As far as I can see there are two ways, both with their drawbacks.

  1. Get the object you are unit testing from the dependency injection system. This is low maintenance as you don’t have to manage anything when you change the framework around. But you are essentially testing the whole system from the point of view of your object, if a component fails it can blow up a lot of unit tests and it may not be apparent which one is failing.

  2. is to manage the dependencies manually in the unit tests, and in some cases create test objects so that you can test each object in isolation. This keeps the unit tests discreet but dramatically increases the maintenance of the unit tests themselves. It also means that you don’t pick up on bugs cause by the way the objects interact on your live system.

Is either approach right or wrong? Should a compromise be used? Has anyone had any success stories either way.

like image 654
Jeremy French Avatar asked Jan 29 '09 10:01

Jeremy French


1 Answers

If you're writing a unit test you should be using mocks for your dependencies and an IoC container shouldn't come into the picture. You should instantiate your class-under-test with mocks for the dependencies injected by hand.

If you're getting your object from the IoC container already wired up then what you're writing is integration tests which are very different.

Your goal for writing a unit test should be to write your test in isolation from the rest of the system.

like image 155
tddmonkey Avatar answered Oct 21 '22 12:10

tddmonkey