Using configuration values can sometimes be hard to get a SUT thoroughly tested. Especially when you have behavior tied to those configuration values.
Consider this simple scenario where we have a component that will throw errors depending on an appsetting value, if the value is false it will silently ignore those errors. Either way you will have code in your component like this:
public class SomeComponent
How would you handle this in your unit tests, adding a real configuration file to your testing assembly will not cover all scenario’s as you could only provide one value for your ‘ThrowErrors’ key, probably you could think of a nice solution to test more scenario’s, but still you need to maintain the extra configuration file for your testing assembly.
What if we could solve this nasty static dependency to ConfigurationManager. Let’s start by creating a simple abstraction
This will give us a nice, clean and mockable abstraction for all your configuration needs. Now add an adapter for the static ConfigurationManager that inherits this abstraction:
Add tests for this adapter so that we have every possible scenario covered. This takes us closer to the real implementation of ‘SomeComponent’ as we now have a mockable dependency to take in. We could stub the AppSettings property to return a NameValueCollection so we can cover every possible scenario. But still this would not clean up the code for our magical method on our component.
Let’s add a string extension to take all that parsing stuff out of the real method.
And finally create a type-safe appsettings class with a dependency to our abstraction
Let’s look at the final solution for our component
Sometimes creating simple infrastructure classes can cleanup existing code and improve it’s readability. But the biggest surplus is we created a way to mock configuration values.