14

I'm trying to unit test a custom ConfigurationSection I've written, and I'd like to load some arbitrary configuration XML into a System.Configuration.Configuration for each test (rather than put the test configuration xml in the Tests.dll.config file. That is, I'd like to do something like this:

Configuration testConfig = new Configuration("<?xml version=\"1.0\"?><configuration>...</configuration>");
MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection");
Assert.That(section != null);

However, it looks like ConfigurationManager will only give you Configuration instances that are associated with an EXE file or a machine config. Is there a way to load arbitrary XML into a Configuration instance?

3 Answers 3

18

There is actually a way I've discovered....

You need to define a new class inheriting from your original configuration section as follows:

public class MyXmlCustomConfigSection : MyCustomConfigSection
{
    public MyXmlCustomConfigSection (string configXml)
    {
        XmlTextReader reader = new XmlTextReader(new StringReader(configXml));
        DeserializeSection(reader);
    }
}


You can then instantiate your ConfigurationSection object as follows:

string configXml = "<?xml version=\"1.0\"?><configuration>...</configuration>";
MyCustomConfigSection config = new MyXmlCustomConfigSection(configXml);

Hope it helps someone :-)

2
  • props for actually answering his question. Apr 1, 2009 at 10:59
  • While the custom Xml read is a good solution, the xml snippet is not correct. The DeserializeSection expects the xml to be just the section piece like <MySection><MyConfig><add key="key" value="value" /></MyConfig></MySection>
    – batta
    Aug 3, 2020 at 8:40
1

I think what you're looking for is ConfigurationManager.OpenMappedExeConfiguration

It allows you to open a configuration file that you specify with a file path (wrapped inside a ExeConfigurationFileMap)

If what the other poster said is true, and you don't wish to create a whole new XML file for testing, then I'd recommend you put your Configuration edits in the Test method itself, then run your tests against the freshly changed configuration data.

0

Looking at the members of the class, I'd say the answer is probably no*. I'm not sure why you'd want to do this anyway, rather than create your own XML configuration file.

*That's no, excluding messy reflection hacks

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.