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;
}
}
}
以上全新的單元測試是從應用配置中讀取一些常量值的代碼 這裏是我的代碼在構造函數中賦值的值。如何對使用靜態類,然後使用ConfigurationElementCollection的方法進行單元測試?
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類閱讀
解決方案
找到解決方案實際上它工作正常的錯誤是在應用程序完成.config
此外,我所面臨的另一個問題是在ConfigSection 對於MVC應用程序的web.config沒有必要爲名稱空間類型=」 型‘ 其中作爲用於單元測試的app.config有必要命名空間類型=’類型,_namespace」
也添加了app.config文件到測試項目 – Krishjs 2014-10-29 07:05:24