简体   繁体   中英

Using Web.config file in unit test

I need a little help in a problem that i got stuck.

I created a unit test and i'm trying to test a class that has a method that uses Membership functionalities. The problem is that Membership use settings from my web project file (Web.config) such as connectString and others.

Is there a way to configure my unit test to read the specificatios from my Web.config located at my web project? I'm using VS2017.

Thank's in advance.

One of the possible solution (which I'd prefer) is to create a common interface to act as a configuration provider, and implement it in a class as follow:

Note: Create this interface and class in a separate assembly which can be consumed in both web application, and unit test projects.

public interface IConfigurationProvider
{
    string GetValue(string key, string valueIfNull = "");
}

using System.Configuration;
public class ConfigurationProvider : IConfigurationProvider
{
    public string GetValue(string key, string valueIfNull = "")
    {
        return (!String.IsNullOrEmpty(ConfigurationManager.AppSettings[key]) 
            ? ConfigurationManager.AppSettings[key] 
            : valueIfNull);
    }
}

Use the instance of ConfigurationProvider class (using DI) in your web application. Whereas in your unit test project you would need to mock the object of "IConfigurationProvider" type and invoke "GetValue" method to return the value of your preference for a particular key.

That means, your web application would need to read config values using this provider instead of directly reading from ConfigurationManager, and your unit test project would need to mock the interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM