简体   繁体   中英

How to test custom configuration section in web.config?

My MVC Web API application has a custom configuration section which is used by the application for config values.

I want to test whether the custom configuration section values populated in the web.config file are correct and GetSection is able to read them correctly. Is there any way to test this without creating another config file for nunit with the exact same values?

Is there any way to test this without creating another config file for nunit with the exact same values?

Yes, you can do this as follows:

Configuration OpenWebConfiguration(string configurationFilePath)
{
    var configurationFileInfo = new FileInfo(configurationFilePath);
    var vdm = new VirtualDirectoryMapping(configurationFileInfo.DirectoryName, true, configurationFileInfo.Name);
    var wcfm = new WebConfigurationFileMap();
    wcfm.VirtualDirectories.Add("/", vdm);
    return WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
}

...
var c = OpenWebConfiguration(pathToWebConfigFile);
var section = c.GetSection(sectionName);
... etc ...

Is there any way to test this without creating another config file for nunit with the exact same values?

No, there isn't. You are required to have a config file in order to test the custom section. And what better place than a unit test project for that? It's seems like the perfect place.

For example you could have the following projects in your solution:

  • MyApp.Configuration (containing the custom section and elements)
  • MyApp.Configuration.Tests (containing an app.config file allowing to test your custom config section)

In addition to the accepted answer, just in case you are looking for an answer on how to avoid adding a separate config file to your Test project and then sync the main config file with your test file, here's a link that describes a neat way of adding the original app/web.config as a link in Test project. You'd essentially be dealing with a single config file. This blog talks about an alternative approach by using TestConigurationSection and the ExeConfigurationFileMap (you may use the equivalent WebConfigurationFileMap )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM