Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding more dependencies to a class sounds like too much work

I am new to dependency injection. I am bit confused hope someone might help me...

Suppose we have a class A which has one dependency (Interface IB) injected through constructor. lets say i have written dozens of test cases written for class A, now at a latter stage i discover that i need one more dependency for class A (say Interface IC). does this mean i have to modify my constructor and all the test cases along with it? As i will be creating objects for class A in the test cases.

EDIT: Also having to modify all test cases increases the possibility that we may make some error in the test case.

like image 866
Umair Ahmed Avatar asked Mar 01 '11 14:03

Umair Ahmed


3 Answers

This is not a problem with DI; it's a problem with the tests. More specifically, you are suffering from the Fragile Test smell.

This can be addressed by using a SUT Factory instead of creating the SUT directly using the new keyword. This will allow you to change the constructor signature in the future without breaking lots of tests.

like image 64
Mark Seemann Avatar answered Oct 17 '22 15:10

Mark Seemann


This is a good question. I think there are two parts of it - actual need to change signature of constructor and act of introducing new dependency.

Adding new parameter to constructor shouldn't be too cumbersome especially taking into account tools for refactoring in contemporary IDE's (e.g. Change Method Signature in Eclipse) that will add parameter and change all places where this constructor is called.

On the other hand introduction of new dependency is always an opportunity for refactoring in my opinion. If your class A can't accomplish its functionality without new dependency maybe it starts to taking too much responsibility.

One trick that could help you to overcome the need for changing code for creation of objects in tests in many place is to use dedicated factory that will take care of preparation of object instance in state ready for testing. You don't have to use the factory in production (DI container does exactly the same) but in test code it might become handy.

like image 44
oiavorskyi Avatar answered Oct 17 '22 14:10

oiavorskyi


Yes, you alter your constructor and your tests. If you discovered that the world was round, you wouldn't continue to test it for flatness, would you? :-) With proper stubs, the extra work will not be that hard. I do it all the time. It is the very core of TDD.

Regards, Morten

like image 30
Morten Avatar answered Oct 17 '22 14:10

Morten