Unit Testing custom ConfigurationElement & ConfigurationElementCollection
我创建了一个自定义的
服务连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | public class ServiceConnection : ConfigurationElement { [ConfigurationProperty("locationNumber", IsRequired = true)] public string LocationNumber { get { return (string) base["locationNumber"]; } set { base["locationNumber"] = value; } } [ConfigurationProperty("hostName", IsRequired = true)] public string HostName { get { return (string) base["hostName"]; } set { base["hostName"] = value; } } [ConfigurationProperty("port", IsRequired = true)] public int Port { get { return (int) base["port"]; } set { base["port"] = value; } } [ConfigurationProperty("environment", IsRequired = true)] public string Environment { get { return (string) base["environment"]; } set { base["environment"] = value.ToUpper(); } } internal string Key { get { return string.Format("{0}|{1}", LocationNumber, Environment); } } } |
ServiceConnection集合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | [ConfigurationCollection(typeof(ServiceConnection), AddItemName ="service", CollectionType = ConfigurationElementCollectionType.BasicMap)] public class ServiceConnectionCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new ServiceConnection(); } protected override object GetElementKey(ConfigurationElement element) { return ((ServiceConnection) element).Key; } public ServiceConnection Get(string locationNumber, string environment ="PRODUCTION") { return (ServiceConnection) BaseGet(string.Format("{0}|{1}", locationNumber, environment)); } public ServiceConnection this[int index] { get { return (ServiceConnection)BaseGet(index); } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } } |
一些测试XML
2在我的生产代码中,我使用
我希望检索一个ServiceConnection对象,并确保所有字段与我在测试XML中设置的输入相匹配。我还想在用户未能填充一个或多个字段时测试功能。
好吧,我最终只是按照@codecaster的建议,使用
我在下面发布了一个样本测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | [Test] public void ShouldProvideFullProductionServiceConnectionRecord() { //NOTE: Open ConfigTests.config in this project to see available ServiceConnection records //Arrange ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap { ExeConfigFilename ="ConfigTests.config" }; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); ServiceConnectionSection section = config.GetSection("AutomationPressDataCollectionServiceConnections") as ServiceConnectionSection; //Act var productionSection = section.Connections.Get("0Q8"); //Assert Assert.AreEqual("0AB0", productionSection.LocationNumber); Assert.AreEqual("DEVSERVER", productionSection.HostName); Assert.AreEqual(1234, productionSection.Port); Assert.AreEqual("DEVELOPMENT", productionSection.Environment); } |
它要求您添加一个新的