当您在单元测试依赖于app.config文件中的值的应用程序时,您如何测试这些值是否被正确读取以及您的程序如何响应配置文件中输入的不正确值?
修改NUnit应用程序的配置文件是荒谬的,但我无法读取要测试的app.config中的值。
编辑:也许我应该澄清一下。我不担心ConfigurationManager无法读取这些值,但我关心的是测试我的程序如何响应读取到的值。
当您在单元测试依赖于app.config文件中的值的应用程序时,您如何测试这些值是否被正确读取以及您的程序如何响应配置文件中输入的不正确值?
修改NUnit应用程序的配置文件是荒谬的,但我无法读取要测试的app.config中的值。
编辑:也许我应该澄清一下。我不担心ConfigurationManager无法读取这些值,但我关心的是测试我的程序如何响应读取到的值。
我通常会将类似读取配置文件的外部依赖项隔离到自己的门面类中,门面类功能很少。在测试中,我可以创建该类的模拟版本并使用它来代替真正的配置文件。您可以创建自己的模拟版本或使用像moq或rhino mocks这样的框架。
这样,您就可以轻松地尝试不同的配置值而无需编写首先编写xml配置文件的复杂测试。读取配置的代码通常非常简单,因此需要进行的测试很少。
您可以在测试设置中在运行时修改配置部分。例如:
// setup
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.Sections.Add("sectionname", new ConfigSectionType());
ConfigSectionType section = (ConfigSectionType)config.GetSection("sectionname");
section.SomeProperty = "value_you_want_to_test_with";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("sectionname");
// carry out test ...
当然,您可以设置自己的辅助方法来更优雅地完成此操作。
您可以调用 ConfigurationManager.AppSettings 的 set 方法来设置特定单元测试所需的值。
[SetUp]
public void SetUp()
{
ConfigurationManager.AppSettings.Set("SettingKey" , "SettingValue");
// rest of unit test code follows
}
当单元测试运行时,它将使用这些值来运行代码
您可以使用 ConfigurationManager
类读取和写入 app.config
文件。
ConfigurationManager.AppSettings["SomeKey"] = "MockValue";
。好答案! - Scott Rippey我在处理web.config时遇到了类似的问题... 我找到了一个有趣的解决方案。您可以封装配置读取功能,例如像这样:
public class MyClass {
public static Func<string, string>
GetConfigValue = s => ConfigurationManager.AppSettings[s];
//...
}
然后通常使用
string connectionString = MyClass.GetConfigValue("myConfigValue");
但在单元测试中,可以通过初始化来"覆盖"该函数,如下所示:
MyClass.GetConfigValue = s => s == "myConfigValue" ? "Hi", "string.Empty";
更多相关信息:
http://rogeralsing.com/2009/05/07/the-simplest-form-of-configurable-dependency-injection/
这对我有效:
public static void BasicSetup()
{
ConnectionStringSettings connectionStringSettings =
new ConnectionStringSettings();
connectionStringSettings.Name = "testmasterconnection";
connectionStringSettings.ConnectionString =
"server=localhost;user=some;database=some;port=3306;";
ConfigurationManager.ConnectionStrings.Clear();
ConfigurationManager.ConnectionStrings.Add(connectionStringSettings);
}
在测试这种类型的东西时,System.Configuration.Abstractions是一件美妙的事情。
这里是GitHub项目网站,其中有一些很好的示例:输入链接说明
这里是NuGet网站:https://www.nuget.org/packages/System.Configuration.Abstractions/
我在几乎所有我的.NET项目中使用它。
嗯,我刚刚遇到了同样的问题... 我想要测试一个被网站引用的业务逻辑项目。 但我只想测试业务逻辑。所以在测试项目的预建事件中,我将 app.Config 文件复制到 bin\debug 文件夹中,并从 app.config 中引用它们...