简体   繁体   English

在单元测试中使用Web.config文件

[英]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. 我创建了一个单元测试,并且试图测试一个类,该类的方法使用Membership功能。 The problem is that Membership use settings from my web project file (Web.config) such as connectString and others. 问题是成员资格使用我的Web项目文件(Web.config)中的设置,例如connectString和其他设置。

Is there a way to configure my unit test to read the specificatios from my Web.config located at my web project? 有没有一种方法可以配置单元测试以从位于Web项目的Web.config中读取规范? I'm using VS2017. 我正在使用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. 注意:在单独的程序集中创建此接口和类,可以在Web应用程序和单元测试项目中使用该接口和类。

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. 在Web应用程序中使用ConfigurationProvider类的实例(使用DI)。 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. 而在单元测试项目中,您需要模拟“ IConfigurationProvider”类型的对象并调用“ GetValue”方法以返回特定键的首选项值。

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. 这意味着,您的Web应用程序将需要使用此提供程序来读取配置值,而不是直接从ConfigurationManager中读取,并且您的单元测试项目将需要模拟该接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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