How to test custom configuration section in web.config?

My MVC Web API application has a custom configuration section that the application uses for configuration values.

I want to check the correctness of the values โ€‹โ€‹of custom configuration parameters populated in the web.config file, and GetSection can read them correctly. Is there a way to verify this without creating another configuration file for nunit with the same values?

+1
source share
3 answers

Is there a way to verify this without creating another configuration file for nunit with the same values?

Yes, you can do it like this:

 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 ... 
+4
source

Is there a way to verify this without creating another configuration file for nunit with the same values?

No no. To verify a user section, a configuration file is required. And what is better than a unit test project? It seems like the perfect place.

For example, your solution may include the following projects:

  • MyApp.Configuration (containing the user section and items)
  • MyApp.Configuration.Tests (containing the app.config file, allowing you to test your own configuration section)
+1
source

In addition to the accepted answer, just in case, if you are looking for an answer on how not to add a separate configuration file to your test project, and then synchronize the main configuration file with the test file, here is a link that describes a neat way to add the source application / web.config as a reference in a test project. You are essentially dealing with a single configuration file. This blog talks about an alternative approach using TestConigurationSection and ExeConfigurationFileMap (you can use the equivalent of WebConfigurationFileMap )

0
source

Source: https://habr.com/ru/post/1200323/


All Articles