使用NUnit对app.config文件进行单元测试

Dan*_*ana 59 .net nunit unit-testing

当你们对一个依赖app.config文件中的值的应用程序进行单元测试时?如何测试这些值是否正确读入以及程序如何对输入到配置文件中的错误值做出反应?

必须修改NUnit应用程序的配置文件是荒谬的,但我无法读取我要测试的app.config的值.

编辑:我想我应该澄清一下.我并不担心ConfigurationManager无法读取值,但我担心测试我的程序如何对读入的值作出反应.

Men*_*elt 44

我通常会隔离外部依赖项,例如在自己的Facade类中读取配置文件,但功能很少.在测试中,我可以创建这个类的模拟版本,实现并使用它而不是真正的配置文件.您可以创建自己的模型或使用像moq或rhino模拟这样的框架.

这样,您可以轻松地尝试使用不同配置值的代码,而无需编写首先编写xml配置文件的复杂测试.读取配置的代码通常非常简单,只需要很少的测试.

  • 可怕的是,这个答案没有得到更多的赞成,而其他关于添加/阅读/编辑配置文件的答案有很多要点.对于读者来说,这个答案是让你的单元测试变得简单和坚固的方法. (4认同)
  • @lain"除了太多抽象层的问题":) (2认同)

小智 31

您可以在测试设置中在运行时修改配置部分.例如:

// 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 ...
Run Code Online (Sandbox Code Playgroud)

您当然可以设置自己的帮助方法来更优雅地执行此操作.


Per*_*ury 24

您可以调用ConfigurationManager.AppSettings的set方法来设置该特定单元测试所需的值.

[SetUp]
public void SetUp()
{
  ConfigurationManager.AppSettings.Set("SettingKey" , "SettingValue");
  // rest of unit test code follows
}
Run Code Online (Sandbox Code Playgroud)

当单元测试运行时,它将使用这些值来运行代码

  • 这是迄今为止为我的目的解决它的最简单方法.我的代码刚刚检查了名为Environment的键是TEST还是LIVE.所以我只是在单元测试方法开始时将键设置为TEST. (2认同)

Ste*_*owe 16

您可以app.config使用ConfigurationManager该类读取和写入该文件

  • 我刚试过这个,效果很好!例如,`ConfigurationManager.AppSettings ["SomeKey"] ="MockValue";`.好答案! (3认同)
  • 啊,我可以在ConfigurationManager集合中设置值吗?我一直认为它是只读的.我想这就是我做出假设的结果:P (2认同)

Tuo*_*nen 11

我在使用web.config时遇到了类似的问题....我找到了一个有趣的解决方案.您可以封装配置读取功能,例如:

public class MyClass {

public static Func<string, string> 
     GetConfigValue = s => ConfigurationManager.AppSettings[s];

//...

}
Run Code Online (Sandbox Code Playgroud)

然后通常使用

string connectionString = MyClass.GetConfigValue("myConfigValue");
Run Code Online (Sandbox Code Playgroud)

但在单元测试中初始化"覆盖"这样的函数:

MyClass.GetConfigValue = s =>  s == "myConfigValue" ? "Hi", "string.Empty";
Run Code Online (Sandbox Code Playgroud)

更多关于它:

http://rogeralsing.com/2009/05/07/the-simplest-form-of-configurable-dependency-injection/