首先,你必须初始化HttpContext.Current
:
HttpContext.Current = new HttpContext(new HttpRequest("", "http://blabla.com", "") {},
new HttpResponse(new StringWriter()));
那么你就必须设置会话:(Necroskillz解释这样做的his blog的方式)
public static void SetFakeSession(this HttpContext httpContext)
{
var sessionContainer = new HttpSessionStateContainer("id",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(), 10, true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc, false);
httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null, CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
}
的下面的片段显示它是如何工作的:
[TestMethod]
public void TestMethod1()
{
HttpContext.Current = new HttpContext(new HttpRequest("", "http://blabla.com", "") {},
new HttpResponse(new StringWriter()));
HttpContext.Current.SetFakeSession();
HttpContext.Current.Session["foo"] = 1;
Assert.AreEqual(1, HttpContext.Current.Session["foo"]);
}
嘲讽的HttpContext是在经典的ASP.NET中很难。我建议你在自己的可模拟类中包装你对HttpContext.Session的引用。 – Joe
数据访问层不应该依赖于HttpContext对象。 – izsl
是的,理想情况下应该是这样。但是,为了遵循这一点,我的项目中的大量代码将不得不被重新考虑。 –