I’ve been reviewing a lot of blog sites lately reguarding testing and unit test practices. One I ran across this morning entitled “Extract and Override refactoring techinque” caught my eye on Taswar Bhatti’s Blog.

Don’t get me wrong here, I tried to read this objectively and understand where he was coming from; however, I am caught by his closing remarks:

There are definitely better ways to design this class by using interface IUser, dependency injection frameworks and mocking frameworks to ease the testing, but those methods would be mentioned later in my blog.

After reviewing the article in detail I must agree whole-heartedly with his closing remark. Using this method to modify the behavior of the object is … well … horrifying. To his credit, he is dead-on with either using an interface or dependency injection. Either will solve this problem fairly well without overloading objects in your test.

So why would this be so bad of an idea? Well, these are just a few reasons:

  • You are now required to make the class public and non-sealed
  • Your test now has intimate knowledge of the implementation. In his example the “Order” base class.
  • You have now created virtual and public/protected methods that should never have been exposed and can now be called by someone else.
  • The fact that you have overloaded the class/method means you have modified it’s behavior for the purpose of testing. Why would you modify what you are trying to test?

To put this simply, it breaks all the rules of encapsulation.

Comments