有没有办法获得基于任意xml的System.Configuration.Configuration实例?

Mat*_*att 14 .net c# testing configuration configurationmanager

我正在尝试对我编写的自定义ConfigurationSection进行单元测试,并且我想将一些任意配置XML加载到每个测试的System.Configuration.Configuration中(而不是将测试配置xml放在Tests.dll中).配置文件.也就是说,我想做这样的事情:

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

但是,看起来ConfigurationManager只会为您提供与EXE文件或计算机配置关联的配置实例.有没有办法将任意XML加载到Configuration实例中?

Oli*_*ain 16

实际上有一种我发现的方式....

您需要定义一个继承自原始配置节的新类,如下所示:

public class MyXmlCustomConfigSection : MyCustomConfigSection
{
    public MyXmlCustomConfigSection (string configXml)
    {
        XmlTextReader reader = new XmlTextReader(new StringReader(configXml));
        DeserializeSection(reader);
    }
}
Run Code Online (Sandbox Code Playgroud)


然后,您可以按如下方式实例化ConfigurationSection对象:

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

希望它可以帮助某人:-)