Access App.Config Settings from Class Library Called through Unit Test Project

前端 未结 4 2051
暗喜
暗喜 2021-02-06 10:26

I have the following setup:

  • ASP.net 3.5 Web Site Project
  • C# Class Library with business logic
  • C# Class Library for unit testing

Th

相关标签:
4条回答
  • 2021-02-06 10:45

    Try WebConfigurationManager.OpenWebConfiguration() method

    Configuration config = WebConfigurationManager.OpenWebConfiguration(@"x:\path\web.config");
                KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
                string connString = appSettings["connString"].Value;
    
    0 讨论(0)
  • 2021-02-06 10:50

    I'd recommend changing the design such that your business-logic layer, instead of having the responsibility to locate configuration settings, is injected with them.

    Your Web app could inject settings it reads from its Web.config file, while your unit test could inject different settings (e.g. connection string to a test database, etc.)

    0 讨论(0)
  • 2021-02-06 10:54

    I just found the solution here. App.config is now being used properly when running my tests through the NUnit GUI.

    Apparently if you are using the NUnit GUI and add the assembly by going through Project > Add Assembly, it doesn't access the app.config. However, if you add the assembly to the NUnit project by dragging the dll from Windows Explorer into the NUnit GUI, then it will access the app.config.

    Alternatively, you can add the assembly through the GUI and then go in the NUnit GUI > Project > Edit, and set the Configuration File Name to the name of the configuration file (VS will set this to name.of.your.dll.config) and set the Project Base to the \bin\Debug directory of your project (these are the extra steps that are done in the background when you drag in the assembly vs adding it manually.

    0 讨论(0)
  • 2021-02-06 11:02

    Just rename app.config to name.of.your.dll.config. It works for me.

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