IConfigurationManager

Introduction

One thing that we should all do more is write unit tests. But sometimes it is hard to write tests for your code. Recently I was testing one method which used static class from .net framework and I didn’t know how to test it.

In my earlier post I talked about reading Web.config file using ConfigurationManager class. And today I would like to show you how to improve this class even more, by using interface instead of static class.

And as a next step how easy it is to test this interface.

Static class

Imagine you are working on a project and you are asked to create class UrlCreator with one method.

This method is using ConfigurationManager on line 4. This method could be written better, but for the sake of this example lets pretend it is complicated method and you need to write the tests to verify the functionality.

However, when we want to test this method, we run into trouble.

We are missing the baseurl path that is saved in a config file. Because there is no config file in Test project.

So how do we fix this? Well we can use the interface and mock the method.

Interface

Same method but with using interface:

Here we need to inject our IConfigurationManager into UrlCreator class. We can do this by simple using Dependency Injection Framework, or we can do it manually as I do it in demo project.

In the method with the interface on the line 4 we can see the change from static class ConfigurationManager to interface IConfigurationManager.

Now the test:

The magic here is in the interface. You can create custom implementation of the interface and therefore easily mock the interface. In the demo project I am using the FakeReader class that returns predictable data for the test.

FakeReader:

Little side note here. You don’t have to create separate class here in order to mock the method. You could easily use some mocking framework like Moq. But that is out of the scope of this article.

Summary

If you need to test a method that uses static class or method, try decouple that static element into interface and than mock the interface instead. The functionality of the static method should be short and predictable, because you are also taking this piece of code out of unit testing. And in order to test this static method you should use some kind of acceptance test.