The problem with dependencies are, that if you want to test a class in a way, that isolates that class from anything else, so you can easily detect changes in functionality, the dependencies must be taken out of the picture. If not, a potential failure could be caused not only by the code we touched, but also by anything that code depends upon. You need to be able to construct an object of the class under test in an way, where you are able to control the object's environment completely.
So how do you remove dependencies? Well, it depends ... (pun fully intended)
In the book "Working Effectively with Legacy Code", Michael Feathers includes a wealth of techniques for breaking dependencies - in fact, about the last third of the book is dedicated to this very topic. And the really great thing is, not only does he teach us a lot of techniques, he also attempts to bestowe within us, the wisdom to choose the optimal technique for any specific type of problem and dependency. Let me just give a very few highlights about constructor parameter dependencies here:
- If you control the source code for the parameter classes, you should be able to inherit those classes to make fakes, and just use those during tests.
- If you don't control the source code, you could create a new class, that wraps the parameter object (a proxy if you will), refactor the constructor to use this new class instead of the parameter class, and have it behave differently during test than when in production.
- A third technique could be to use mocking to abstract away the dependencies.
A few highlights about references to globals too:
- You could wrap your globals in a static class, that exposes those through static properties, and making the properties behave differently during test than when in production.
- You could try to remove the global all together by injecting the value as a constructor parameter or as a property.
These techniques and many more are explained in the book in crystal clear details, and with example code to match. As I read through the book, I can't help but thinking, that I should have read this book back in 2005, when it was published, because it would have saved me so much pain and anguish by now ... well, in this case, the phrase "better late than never" is very appropriate: These techniques will continue to be valuable for a long time. So no excuses left - Read the book!
Ingen kommentarer:
Send en kommentar