How to test custom configuration section in web.co

2019-07-12 20:30发布

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?

3条回答
做个烂人
2楼-- · 2019-07-12 20:51

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 ...
查看更多
一夜七次
3楼-- · 2019-07-12 21:06

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)
查看更多
SAY GOODBYE
4楼-- · 2019-07-12 21:15

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)

查看更多
登录 后发表回答