0

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.

1
  • 3
    Easiest way will be to copy the web.cofig contents from the project you're trying to test into the app.config of unit test project. Commented Feb 22, 2018 at 5:13

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.