Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

Visual Studio Unit test - Custom Config Section

I'm writing some unit tests, this unit test do use code in an external library, this library expects the config file to contain some information. I know that to use App.config in my UnitTest, I need to mark my TestMethod with [DeploymentItem("App.config")], but as far as I know, this will by default look for configuration tags in the section <appSettings>. How can I specify if my App.config defines a custom config section?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="MySettingSection" type="System.Configuration.AppSettingsSection" />
  </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>

  <MySettingSection>
    <add key="ApplicationName" value="My Test Application" />
  </MySettingSection>

</configuration>

Upvotes: 0

Views: 2098

Answers (1)

Mat&#237;as Fidemraizer
Mat&#237;as Fidemraizer

Reputation: 64923

I know that to use App.config in my UnitTest, I need to mark my TestMethod with [DeploymentItem("App.config")]

This statement is wrong: App.config is deployed by default. This is true in Visual Studio 2012 and above (I can't confirm that in earlier versions because I don't have any of them installed in my machine).

How can I specify if my App.config defines a custom config section?

Add the required configuration section declarations in the App.config and it will work as you expect:

<configSections>
    <section name="YourSection" type="Assembly Qualified Path to the class representing your section" />
  </configSections>

Check this other old answer I did a long time ago (it should guide you on how configuration model works to set configuration and settings for satellite assemblies in your App.config):

Update

In some comment, OP said:

By using my example, if I write the following inside my unit test ConfigurationManager.AppSettings["ApplicationName"]; it will only return null. Is there any Attribute which defines where the UnitTest should look after the "ApplicationName"?

Note your custom declared System.Configuration.AppSettingsSection configuration section isn't the default <appSettings> accessed by ConfigurationManager.AppSettings["ApplicationName"].

In your case, you should access that section this way:

Configuration config =
              ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("MySettingSection");
string appName = appSettings["ApplicationName"];

Upvotes: 1

Related Questions