【发布时间】:2014-10-29 07:04:03
【问题描述】:
public class ConfigSection : ConfigurationSection
{
public static ConfigSection GetConfigSection()
{
return (ConfigSection)System.Configuration.ConfigurationManager.
GetSection("ConfigSections");
}
[System.Configuration.ConfigurationProperty("ConstantsSettings")]
public ConstantSettingCollection ConstantsSettings
{
get
{
return (ConstantSettingCollection)this["ConstantsSettings"] ??
new ConstantSettingCollection();
}
}
public class ConstantSettingCollection : ConfigurationElementCollection
{
public ConstantElements this[object key]
{
get
{
return base.BaseGet(key) as ConstantElements;
}
set
{
if (base.BaseGet(key) != null)
{
base.BaseRemove(key);
}
this.BaseAdd(this);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new ConstantElements();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ConstantElements)element).Key;
}
}
public class ConstantElements : ConfigurationElement
{
[ConfigurationProperty("key", IsRequired = true)]
public string Key
{
get
{
return this["key"] as string;
}
}
[ConfigurationProperty("val", IsRequired = true)]
public string Constants
{
get { return this["value"] as string; }
}
}
}
public class ConstantHelper
{
public static string ConstantForLog
{
get
{
return ConfigSection.GetConfigSection().ConstantsSettings["ConstantForLog"].Constants;
}
}
}
上面的单元测试完全是新的代码,它从应用程序配置中读取一些常量值 这是我在构造函数中的代码已经分配了值。
public class HomeController
{
protected string constants;
public HomeController()
{
constants = ConstantHelper.ConstantForLog;
}
}
测试代码
[TestClass]
public class HomeControllerTester
{
[TestMethod]
public void Initialize_Tester()
{
//Creating Instance for the HomeController
HomeController controller = new HomeController();
}
}
在调试时发现 Appsettings 不被 ConstantHelper 类读取
解决方案
发现解决方案实际上它工作正常错误是在 app.config 中完成的
我遇到的另一个问题是在 ConfigSection 对于 MVC 应用程序 web.config,不需要命名空间 type="type" 至于单元测试 app.config 需要命名空间 type="type,_namespace"
【问题讨论】:
-
已将 app.config 文件添加到测试项目中
标签: c# asp.net-mvc unit-testing