When developing an ASP .NET MVC or WebAPI based application, we eventually need to read configurations from <appSettings> section of Web.Config file. Here is an example entry from my imaginary project:

If we need to get a specific settings value, easiest way to get this:

This is pretty fine. However, it does make your code difficult to unit test. Because, when you are running tests, ConfigurationManager.AppSettings may not behave the way it behaves in your web application. So, your tests may eventually fail even if there is nothing wrong with you business logic.

To make codes testable, I prefer having a service/provider for AppSettings. This is injected as a dependency wherever I need it. Here is the simple wrapper:

Also, it would be better to configure this wrapper as a singleton or single instance in your DI container.

Now, you can easily mock this IAppSettings and run your tests without worrying about ConfigurationManager.

Here is a sample test written using MSpec and NSubstitute:

Happy testing. :)