我試圖單元測試一些代碼,它從HttpContext.Current.Application
中讀取一個值,但由於它無法檢索值而一直保持失敗。使用HttpContext.Application進行單元測試
我試過創建自己的HttpContext
,設置HttpContext.Current
,然後寫入值,但它似乎沒有存儲新的值。
代碼引用的HttpContext.Current.Application
public static void UpdateApplicationVariable(string keyToUpdate, object toSave)
{
HttpContext.Current.Application.Lock();
HttpContext.Current.Application[keyToUpdate] = toSave;
HttpContext.Current.Application.UnLock();
}
public static object GetApplicationVariable(string keyToReturn)
{
return HttpContext.Current.Application[keyToReturn];
}
設置代碼
HttpContext.Current = new HttpContext(
new HttpRequest(null, "http://tempuri.org", null),
new HttpResponse(null)
);
UpdateApplicationVariable("GeneralSettings", new GeneralSettings()
{
NumberDecimalPlaces = 2
});
//settings is null
GeneralSettings settings = GetApplicationVariable("GeneralSettings") as GeneralSettings;
您是否檢查過其他人如何模擬HttpContext(https://www.bing.com/search?q=Unit+testing+with+HttpContext.Application)或考慮將該訪問抽象爲依賴關係? –