我有一个网络服务,我正在尝试对其进行单元测试。在服务中,它从 HttpContext
中提取几个值,如下所示:
m_password = (string)HttpContext.Current.Session["CustomerId"];
m_userID = (string)HttpContext.Current.Session["CustomerUrl"];
在单元测试中,我使用简单的工作请求创建上下文,如下所示:
SimpleWorkerRequest request = new SimpleWorkerRequest("", "", "", null, new StringWriter());
HttpContext context = new HttpContext(request);
HttpContext.Current = context;
但是,每当我尝试设置 HttpContext.Current.Session
HttpContext.Current.Session["CustomerId"] = "customer1";
HttpContext.Current.Session["CustomerUrl"] = "customer1Url";
我收到空引用异常,提示 HttpContext.Current.Session
为空。
有什么方法可以在单元测试中初始化当前 session 吗?
最佳答案
您可以像这样创建一个新的 HttpContext
来“伪装”它:
我已经采用该代码并将其放在静态帮助程序类中,如下所示:
public static HttpContext FakeHttpContext()
{
var httpRequest = new HttpRequest("", "http://example.com/", "");
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponse);
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 });
return httpContext;
}
或者不使用反射来构造新的 HttpSessionState
实例,您可以将 HttpSessionStateContainer
附加到 HttpContext
(根据 Brent M . Spell 的评论):
SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);
然后您可以在单元测试中调用它,例如:
HttpContext.Current = MockHelper.FakeHttpContext();
关于c# - 在单元测试中设置 HttpContext.Current.Session,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9624242/