I thought I might take the opportunity to talk about a technique that we use to isolate our code from ConfigurationManager and also other system classes such as the system DateTime, using the language constructs built within the .Net Framework version 3.5 and above. I’m not saying that this technique is better than the Castle Dictionary Adapter method but it just highlights an alternative approach that is possible without using third party assemblies.
Ok so using Ben’s example, because I’m too lazy to think up my own, we have an application configuration value for our EnableNewsLetterSignup.
In our code we pull out the value using the static method on the ConfigurationManager class like so.
Ok so nothing new here but when it comes to testing this code it means that we have to have a configuration file for our unit test project (which is bad) and we can only ever test one path through the code without changing the value of the configuration file. Which means we some untestable code without doing some configuration Kung Fu on our config file which is more work than we should have to do.
Wrapping It Up
The technique we use is to wrap our class up in a static wrapper class which we will call Config. For our corresponding application setting we add a public static field of the same name for clarity, of type Func<string>. Now the important thing is we give it it’s default behaviour which in this case is to go off and use our old friend ConfigurationManager to determine whether or not our newsletter is enabled or not.
Writing Our Code
Now going back to our code where we use the application setting it will now look something like this.
Testing Our Code
So now when we want to unit test this piece of code we simply change the default behaviour of our Config class to the behaviour we want to test. See line 5 below, where we force it to return false for the purpose of our unit test. We now have total control over what our supposedly configuration value is without ever having to touch the file system.
As I said earlier this technique can also be quite useful for isolating other system dependant classes such as code that uses the DateTime.Now property. Sometimes if you want to logic concerning dates and times it can be pretty hard to control the flow of the code because the DateTime is generated by the system. How for example do you test something if you need to be some date in the future or some date in the past. The code below can be used in the same way to isolate our tests from the underlying call to the DateTime.Now which can be overriden as required to give the behaviour we want.
This approach offers an alternative solution to using the Castle Dictionary Adapter, and although it requires writing slightly more code it does mean that it is one less assembly that you have to reference in your project which can be a good thing sometimes.