2008-08-21 32 views
14

我想单元测试我编写的一个自定义ConfigurationSection,并且我想为每个测试加载一些任意配置XML到System.Configuration.Configuration(而不是将测试配置xml放在Tests.dll.config文件中也就是说,我希望做这样的事情:有没有办法根据任意xml获取System.Configuration.Configuration实例?

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

但是,它看起来像ConfigurationManager只会给你所有与EXE文件或机器配置相关的配置情况下有没有办法来。将任意XML加载到配置实例中?

回答

15

其实是有,我发现了一种方法....

您需要定义一个新的类从原来的配置节继承如下:

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


然后,您可以实例您ConfigurationSection对象如下:

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

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

+0

实际回答他的问题的道具。 – 2009-04-01 10:59:50

0

看着这个类的成员,我会说答案可能不是*。我不确定你为什么要w ant无论如何都要这样做,而不是创建自己的XML配置文件。

*这是没有,不凌乱反射黑客

1

我想你要寻找的是ConfigurationManager中。 OpenMappedExeConfiguration

它可以让你打开你的文件路径(包内ExeConfigurationFileMap

如果什么其他的海报说的是真的指定配置文件,并且不希望创建一个全新的XML文件进行测试,那么我建议您将配置编辑置于Test方法本身,然后针对刚更改的配置数据运行测试。

相关问题