We have a number of .NET objects in our legacy code which load in configuration from app.config files. This can be a bit of a problem when you want to get a class under test - as you almost certainly want to reconfigure the object in more than one way.
For example I have a class
using System.Configuration; |
To break this dependancy you should create a new constructor which accepts a name value collection. Move the logic into this new constructor and then replace the static calls to AppSettings with calls to your new input variable.
using System.Collections.Specialized; |
The great thing about this approach is that the behaviour of the class has not changed. This is important, because your class is not under test yet (but it soon will be!). Now you can put the class under test without needing app config files.
A word of warning. You must be careful and check for subsequent calls to AppSettings in other method calls. If other methods use the static method call, then you will need to either hold a reference to the configuration parameters and use this later on, or else change the behaviour of the class to setup what ever the methods initialise in the construction logic.
technorati tags: Refactoring, TDD, C#

