[英]Is there a way to get a System.Configuration.Configuration instance based on arbitrary xml?
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: 我正在尝试对已编写的自定义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);
However, it looks like ConfigurationManager will only give you Configuration instances that are associated with an EXE file or a machine config. 但是,看来ConfigurationManager仅会为您提供与EXE文件或计算机配置关联的Configuration实例。 Is there a way to load arbitrary XML into a Configuration instance?
有没有一种方法可以将任意XML加载到Configuration实例中?
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: 然后可以实例化ConfigurationSection对象,如下所示:
string configXml = "<?xml version=\"1.0\"?><configuration>...</configuration>";
MyCustomConfigSection config = new MyXmlCustomConfigSection(configXml);
Hope it helps someone :-) 希望它可以帮助某人:-)
I think what you're looking for is ConfigurationManager. 我认为您正在寻找的是ConfigurationManager。 OpenMappedExeConfiguration
OpenMappedExeConfiguration
It allows you to open a configuration file that you specify with a file path (wrapped inside a ExeConfigurationFileMap ) 它允许您打开使用文件路径指定的配置文件(包装在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. 如果其他提示者说的是正确的,并且您不想创建一个全新的XML文件进行测试,那么我建议您将“配置”编辑内容放入“测试”方法本身,然后针对新更改的配置运行测试数据。
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.
我不确定为什么还是要这样做,而不是创建自己的XML配置文件。
*That's no, excluding messy reflection hacks *不是,不包括混乱的反射黑客
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.