Unit testing the app.config file with NUnit

后端 未结 13 2318
夕颜
夕颜 2020-12-04 16:37

When you guys are unit testing an application that relies on values from an app.config file? How do you test that those values are read in correctly and how your program re

13条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 17:09

    I was facing similar problems with web.config.... I find an interesting solution. You can encapsulate configuration reading function, e.g. something like this:

    public class MyClass {
    
    public static Func 
         GetConfigValue = s => ConfigurationManager.AppSettings[s];
    
    //...
    
    }
    

    And then normally use

    string connectionString = MyClass.GetConfigValue("myConfigValue");
    

    but in unit test initialize "override" the function like this:

    MyClass.GetConfigValue = s =>  s == "myConfigValue" ? "Hi", "string.Empty";
    

    More about it:

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

提交回复
热议问题