在单元测试 asp.net 应用程序时如何使用 web.config

我从单元测试开始,我有一个使用 web.config 作为连接字符串的方法。

我希望能用

[DeploymentItem("web.config")]

to get the web config file, this still leaves me with null reference exceptions (that'd be what I write my next test for).

如何使用试图测试的项目中包含的配置文件?

我正在使用 VS2008中包含的测试框架,如果这有什么不同的话。

谢谢

50751 次浏览

单元测试项目应该有自己的配置文件。

在测试项目上,可以选择“添加”、“新建项”、“应用程序配置文件”。

这个文件的行为与 web.config 完全一样,但是对于您的单元测试而言。

您将希望您的结果是定义良好和可重复的。为此,您需要处理已知的数据,以便能够清楚地定义正常情况和边界情况。在我的工作中,这是 一直都是一个特定的服务器和数据集,所以单元测试模块有内置的连接字符串。其他人更喜欢使用 UnitTestingproject 中的连接字符串。我从来没有看到任何人推荐使用该网站的配置文件!(发展或其他)

如果需要连接字符串,则不需要编写单元测试(假设使用连接字符串访问数据库)。单元测试不应该与外部环境交互。你会想在每次检查后运行它们,所以它们最好以光速运行。

对于单元测试,需要将代码与数据库隔离开来。修改您的测试(以及您正在测试的代码,如果必要的话) ,这样您就不需要到数据库去测试它们。

将 web.config 文件复制到“/bin”文件夹中,并将其重命名为“ AppName.dll.config”。

其中“ AppName”-是结果程序集的名称。

我用过很多次这种黑客技术。

可以使用 OpenMappedExeConfiguration从任何位置加载 web.config 或 app.config。确保将 System.Configuration添加到项目的引用中。

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap()
fileMap.ExeConfigFilename = @"c:\my-web-app-location\web.config"


Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
string connectionString = config.AppSettings.Settings["ConnectionString"].Value;

这是 web.config,非常标准。

<?xml version="1.0"?>
<configuration>
<configSections>
</configSections>
<appSettings>
<add key="ConnectionString" value="Data Source=XXXX;Initial Catalog=XXX; Trusted_Connection=True;"/>
</appSettings>
</configuration>

二○一七年九月二十九日最新消息

我创建了一个类,使从文件中读取 AppSettings 变得更加容易。我从 Zp Bappi得到的灵感。

public interface IAppSettings
{
string this[string key] { get; }
}


public class AppSettingsFromFile : IAppSettings
{
readonly Configuration Config;


public AppSettingsFromFile(string path)
{
var fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = path;
Config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
}


public string this[string key]
{
get
{
return Config.AppSettings.Settings[key].Value;
}
}
}

下面是如何使用该类。

IAppSettings AppSettings = new AppSettingsFromFile(@"c:\my-web-app-location\web.confg");
string connectionString = AppSettings["ConnectionString"];

我建议对配置读取部分进行抽象,以便可以对其进行模拟。类似这样的事情,请看乔恩 · 林德海姆的回复