Unit testing the app.config file with NUnit

后端 未结 13 2136
夕颜
夕颜 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 16:44

    Well, I just had the same problem... I wanted to test a BL project that is referenced from a web site . but i wanted to test the BL only. So in the pre-build event of the test project I copy the app.Config files into the bin\debug folder and reference them from the app.config ...

    0 讨论(0)
  • 2020-12-04 16:48

    You can always wrap the reading-in bit in an interface, and have a specific implementation read from the config file. You would then write tests using Mock Objects to see how the program handled bad values. Personally, I wouldn't test this specific implementation, as this is .NET Framework code (and I'm assuming - hopefully - the MS has already tested it).

    0 讨论(0)
  • 2020-12-04 16:53

    You can modify your config section at runtime in your test setup. E.g:

    // 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 ...
    

    You can of course setup your own helper methods to do this more elegantly.

    0 讨论(0)
  • 2020-12-04 16:53

    You can both read and write to the app.config file with the ConfigurationManager class

    0 讨论(0)
  • 2020-12-04 16:58

    That worked for me:

     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);
      }
    
    0 讨论(0)
  • 2020-12-04 17:00

    System.Configuration.Abstractions is a thing of beauty when it comes to testing this kind of stuff.

    Here is the GitHub project site with some good examples: enter link description here

    Here is the NuGet site: https://www.nuget.org/packages/System.Configuration.Abstractions/

    I use this in almost all of my .NET projects.

    0 讨论(0)
提交回复
热议问题