Testing methods with reference to Web.Config in .Net C #

I searched a lot and still have not found a reliable solution. Suppose you have methods in your application. These methods use "System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration" to access some parameters in web.config. If you try to test these methods, your tests will fail because your test project does not have web.config.

What is the best way to solve this problem. For projects with a simple configuration file, I usually use a method like the facade method.

public class Config
{
    public static String getKeyValue(String keyName)
    {
        if (keyName == String.Empty) return String.Empty;
        String result = "";

        System.Configuration.Configuration rootWebConfig1 =
           System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
        if (rootWebConfig1.AppSettings.Settings.Count > 0)
        {
            System.Configuration.KeyValueConfigurationElement reportEngineKey =
                rootWebConfig1.AppSettings.Settings[keyName];

            if (reportEngineKey != null)
            {
                result = reportEngineKey.Value;

            }

        }

        return result;
    }
}

Every time I tried to set the path for OpenWebConfiguration (), I got the error "Relative virtual path not allowed"

+3
source share
2

, " " . , :

public interface IConfig
{
    string GetSettingValue(string settingName);
}

"" :

public sealed class Config : IConfig
{
    public string GetSettingValue(string settingName)
    {
        // your code from your getKeyValue() method would go here
    }
}

, , ( ):

public void DoStuff(IConfig configuration)
{
    string someSetting = configuration.GetSettingValue("ThatThingINeed");
    // use setting...
}

, DoStuff Config. , (Moq, JustMock, RhinoMocks ..), IConfig, .config, ( ).

public class ConfigMock : IConfig
{
    private Dictionary<string, string> settings;

    public void SetSettingValue(string settingName, string value)
    {
        settings[settingName] = value;
    }

    public string GetSettingValue(string settingName)
    {
        return settings[settingName];
    }
}

[Test]
public void SomeExampleTest()
{
    var config = new ConfigMock();
    config.SetSettingValue("MySetting", "SomeValue");

    var underTest = new MyClass();
    underTest.DoStuff(config);
}
+2

- , ​​ moq. , , , , , , .

0

All Articles