Gil Grossman
Gil Grossman

Reputation: 139

How to mock configuration for C# application

I wrote a C# application and would like to mock the configuration values. For example, I configure a path for file creation on remote machine and would like to create it locally when testing.

I thought of creating a wrapper class for the configuration that implements and interface, using this methodology one may mock the interface and return mocked values.

public interface IConfigurationProvider
{
   string GetFileOutputPath(string path);
}

public class ConfigurationWrapper : IConfigurationProvider
{
    return ConfigurationManager.AppSettings.Get("FileOutputPath");
}

Configuration:

<configuration>
    <appSettings>
        <add key="FileOutputPath" value="RemoteServerPath" />
    </appSettings>
</configuration>

This approach sure does the work, but is it best practice for this scenario?

Upvotes: 2

Views: 2914

Answers (1)

Nkosi
Nkosi

Reputation: 247631

As far as best practice, that would be a matter of opinion. In terms of clean, testable, maintainable code, the approach is commonly used.

Here is a variation of your approach. (basically provides the same functionality)

using System.Configuration;

public interface IApplicationSettings {
    string this[string setting] { get; }
}

public class ConfigAppSettings : IApplicationSettings {
    public string this[string setting] {
        get { return ConfigurationManager.AppSettings[setting]; }
    }
}

public interface IConnectionStrings {
    string this[string name] { get; }
}

public class ConfigConnectionStrings : IConnectionStrings {
    public string this[string name] {
        get { return ConfigurationManager.ConnectionStrings[name].ConnectionString; }
    }
}

Upvotes: 1

Related Questions