我试图单元测试一些代码,它从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)或考虑将该访问抽象为依赖关系? –